-
描述
-
这有一个迷宫,有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,10表示道路,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
-
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
初学DFS,想法很菜,勿喷。。。谈一下解其他迷宫题的思路,有的题可能没有设边界(不像这道题周围都是墙 封闭的),这时候会有bug,可能程序找的解不是在区域内的路线,可能会出这个区域,这时候要多加个限制条件,让 0 < 坐标 < 行数、列数;或是设置map地图数组时,在原有的区域周围都加上一堵墙,用墙圈起来,这样也能达到效果
DFS解法:
#include<cstdio>
#include<algorithm>
#define Q 10000
using namespace std;
int x,y,ex,ey,ans;
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1}; // dx[4],dy[4] 是为了控制 上下左右 四个方向的
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 DFS(int x,int y,int c) //找到满足条件的最优解
{
if(x==ex&&y==ey)
{
if(c<ans) // 判断此时的 c 是否为最优解
{
ans=c;
}
}
else
{
for(int i=0;i<4;i++)
{
int nx=x+dx[i];
int ny=y+dy[i];
if(!map[nx][ny]&&c<ans-1) // 限制此时的 c 比上一步的解 ans-1小
{
map[nx][ny]=1;
DFS(nx,ny,c+1); // 这里 c 还要加 1,这就可以解释上面判断要 a<ans-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);
ans=Q; // 这里先给 ans 一个较大的值,要筛选 c
map[x][y]=1;
DFS(x,y,c);
printf("%d\n",ans);
map[x][y]=0; // 为了不影响下一组数据的测试,初始化该点
}
return 0;
}
BFS解法:
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
int dx[4]={-1,1,0,0};
int dy[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 };
bool vis[9][9];
int kx,ky,ex,ey;
struct node
{
int x,y,step;
};
int BFS()
{
node s;
s.x=kx, s.y=ky, s.step=0;
vis[kx][ky]=1;
queue<node> qu;
qu.push(s);
while( !qu.empty() )
{
node now=qu.front();
qu.pop();
if(now.x==ex&&now.y==ey)
return now.step;
for(int i=0;i<4;i++)
{
node next;
next.x=now.x+dx[i];
next.y=now.y+dy[i];
next.step=now.step;
if(!vis[next.x][next.y]&&!map[next.x][next.y])
{
vis[next.x][next.y]=1;
next.step+=1;
qu.push(next);
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(vis,0,sizeof(vis));
scanf("%d %d %d %d",&kx,&ky,&ex,&ey);
printf("%d\n",BFS());
}
return 0;
}