Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
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)
bfs打印路径。
CODE:
#include<stdio.h>
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
struct Step
{
int x;
int y;
//Step(int_x,int_y):x(0),y(0);
};
int maze[5][5],vis[5][5],d[5][5];
int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
void print(int x,int y)
{
int p=d[x][y];
if(p!=-1)
print(x-dx[p],y-dy[p]);
printf("(%d, %d)\n",x,y);
}
void bfs(int sx,int sy,int fx,int fy)
{
queue<Step>que;
Step now={sx,sy};
que.push(now);
vis[sx][sy]=1;
while(!que.empty())
{
now=que.front();
que.pop();
for(int i=0;i<4;i++)
{
Step n={now.x+dx[i],now.y+dy[i]};
if(n.x>=sx&&n.x<=fx&&n.y>=sy&&n.y<=fy&&!vis[n.x][n.y]&&maze[n.x][n.y]!=1)
{
d[n.x][n.y]=i;
vis[n.x][n.y]=1;
que.push(n);
}
if(n.x==fx&&n.y==fy)
break;
}
}
print(fx,fy);
}
int main()
{
//freopen("A.txt","r",stdin);
memset(vis,0,sizeof(vis));
memset(d,-1,sizeof(d));
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
{
scanf("%d",&maze[i][j]);
}
bfs(0,0,4,4);
return 0;
}