Description
定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
输出的方式贼有意思
不过,,好像并没有保证最短的过程啊,只是走到了最后而已。
map跟vis可以合并~
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=1001;
bool map[maxn][maxn];
int dx[]={1,0,-1,0},dy[]={0,1,0,-1};
//bool vis[maxn][maxn];
struct node
{
int x,y,z;
}foot[maxn][maxn],arr[maxn];;
int bfs()
{
queue<node>q;
q.push((node){0,0,0});
map[0][0]=1;
while(!q.empty())
{
node f=q.front();
q.pop();
if(f.x==4&&f.y==4) return f.z;
//if(vis[f.x][f.y]) continue;
for(int i=0;i<=3;i++)
{
node n;
n.x=f.x+dx[i];
n.y=f.y+dy[i];
n.z=f.z+1;
if(0<=n.x&&n.x<=4&&0<=n.y&&n.y<=4)
{
if(!map[n.x][n.y])
// if(!vis[n.x][n.y]&&!map[n.x][n.y])
{
q.push(n);
//vis[n.x][n.y]=1;
map[n.x][n.y]=1;
foot[n.x][n.y].x=f.x;
foot[n.x][n.y].y=f.y;
}
}
}
}
return 0;
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
scanf("%d",&map[i][j]);
int len=bfs();
int a=4,b=4;
for(int i=0;i<len;i++)
{
arr[i].x=foot[a][b].x;
arr[i].y=foot[a][b].y;
a=arr[i].x;
b=arr[i].y;
}
for(int i=len-1;i>=0;i--)
{
printf("(%d, %d)\n",arr[i].x,arr[i].y);
}
printf("(4, 4)\n");
return 0;
}