描述
这有一个迷宫,有0~8行和0~8列:
1,1,1,1,1,1,1,1,1
1,0,0,1,0,0,1,0,1
1,0,0,1,1,0,0,0,1
1,0,1,0,1,1,0,1,1
1,0,0,0,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,0,0,0,1
1,1,1,1,1,1,1,1,1
0表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
输入
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出
输出最少走几步。
样例输入
2
3 1 5 7
3 1 6 7
样例输出
12
11
对于DFS要注意两点:
一:递归结束的条件,要清除递归会在什么时间结束。
二:递归继续执行下去的条件。
#include<cstdio>
#define M 1000
int x,y,ex,ey,ans;
int px[4]={-1,1,0,0};//代表那一点的四个方向坐标
int py[4]={0,0,-1,1};
int map[9][9]={
1,1,1,1,1,1,1,1,1,
1,0,0,1,0,0,1,0,1,
1,0,0,1,1,0,0,0,1,
1,0,1,0,1,1,0,1,1,
1,0,0,0,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,0,0,0,1,
1,1,1,1,1,1,1,1,1, };
void f(int x,int y,int c)
{
if(x==ex&&y==ey)
{
if(c<ans)
ans=c;
}
else
{
for(int i=0;i<4;i++)
{
int nx=x+px[i];//不能设为全局变量
int ny=y+py[i];
if(map[nx][ny]==0&&c+1<ans)
{
map[nx][ny]=1;
f(nx,ny,c+1);
map[nx][ny]=0; //找其他方向的点
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int c=0;
scanf("%d%d%d%d",&x,&y,&ex,&ey);
map[x][y]=1;
ans=M;
f(x,y,c);
printf("%d\n",ans);
map[x][y]=0;
}
return 0;
}
用BFS也能做这道题
创建一个标记数组,用于记录是否已经走过这一点,根据先进先出策略,先标记的点肯定最近,其他点再走这一点相当于绕圈,这时一定不是最近的。
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int x,y,ex,ey,cnt,mark[10][10];
int dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
int map[9][9]={
1,1,1,1,1,1,1,1,1,
1,0,0,1,0,0,1,0,1,
1,0,0,1,1,0,0,0,1,
1,0,1,0,1,1,0,1,1,
1,0,0,0,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,1,0,0,1,
1,1,0,1,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,
};
struct node
{
int x,y,step;
}a,temp;
void bfs()
{
int i;
a.x=x;
a.y=y;
a.step=0;
memset(mark,0,sizeof(mark));
queue<node>q;
mark[x][y]=1;
q.push(a);
while(!q.empty())
{
a=q.front();
q.pop();
for(i=0;i<4;i++)
{
temp.x=a.x+dir[i][0];
temp.y=a.y+dir[i][1];
temp.step=a.step+1;
if(temp.x>=0&&temp.x<9&&temp.y>=0&&temp.y<9&&mark[temp.x][temp.y]==0&&map[temp.x][temp.y]==0&&temp.step<cnt)
{
if(temp.x==ex&&temp.y==ey)
{
if(cnt>temp.step)
cnt=temp.step;
continue;
}
mark[temp.x][temp.y]=1;
q.push(temp);
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d%d",&x,&y,&ex,&ey);
if(x==ex&&y==ey)
{
printf("0\n");
continue;
}
cnt=100;
bfs();
printf("%d\n",cnt);
}
return 0;
}