J. 迷宫问题(migong) [ Problem 1737 ] [ Discussion ]
Description
设有一个N∗N(2≤N<10)方格的迷宫,入口和出口分别在左上角和右上角。迷宫格子中分别放0和1,0表示可通,1表示不能,入口和出口处肯定是0。迷宫走的规则如下所示:即从某点开始,有八个方向可走,前进方格中数字为0时表示可通过,为1时表示不可通过,要另找路径。找出所有从入口(左上角)到出口(右上角)的路径(不能重复),输出路径总数,如果无法到达,则输出0。
Samples
Input Copy
3
0 0 0
0 1 1
1 0 0
Output
2
Source
信息学一本通 初赛篇 算法部分
Discussions
No more discussions
dfs 一条路走到黑 深度优先
More>>
#include<bits/stdc++.h>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
ll read(){
ll res = 0, ch, flag = 0;if((ch = getchar()) == '-')flag = 1;else if(ch >= '0' && ch <= '9')res = ch - '0';while((ch = getchar()) >= '0' && ch <= '9' )res = res * 10 + ch - '0';return flag ? -res : res;}
const int maxn =1e6+199 ;
ll sum=0,maxa=-1;
ll n,m,k,w,ans=0,cnt=0;
ll a[300][300];
ll b[300][300];
ll dis[8][2]={
{
1,0},{
-1,0},{
0,1},{
0,-1},{
1,1},{
1,-1},{
-1,1},{
-1,-1}};
ll mod=1e9+7;
struct node{
int x,y;
}st,en;
queue<node>p;
void dfs(int xx,int yy)
{
if(xx==1&&yy==n)
{
cnt++;
return;
}
int x,y;
for(int i=0;i<=7;i++)
{
x=xx+dis[i][0];
y=yy+dis[i][1];
if(x>=1&&x<=n&&y>=1&&y<=n&&a[x][y]==0&&b[x][y]==0)
{
b[x][y]=1;///我先走这条道
dfs(x,y);
b[x][y]=0;///不走这个
}
}
return;
}
int main()
{
n=read();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
cin>>a[i][j];
}
b[1][1]=1;
dfs(1,1);
cout<<cnt;
return 0;
}