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)
代码:
#include <cstdio>
#include <queue>
using namespace std;
int maze[5][5];
bool mark[5][5];
struct N{
int x,y,pre;
}q[50];
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int front=0,rear=0;
void bfs(int sx,int sy,int ex,int ey){
q[0].x=sx;q[0].y=sy;q[0].pre=-1;
rear++;
mark[sx][sy]=true;
while(front<rear){
for(int i=0;i<4;i++){
int nx=q[front].x+dir[i][0];
int ny=q[front].y+dir[i][1];
if(nx<0||nx>=5||ny<0||ny>=5) continue;
if(maze[nx][ny]==1) continue;
if(mark[nx][ny]==true) continue;
q[rear].x=nx;
q[rear].y=ny;
q[rear].pre=front;
rear++;
mark[nx][ny]=true;
if(nx==ex&&ny==ey) return;
}
front++;
}
}
void print(N now){
if(now.pre==-1){
printf("(%d, %d)\n",now.x,now.y);
return;
}
print(q[now.pre]);
printf("(%d, %d)\n",now.x,now.y);
}
int main(){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
scanf("%d",&maze[i][j]);
mark[i][j]=false;
}
}
bfs(0,0,4,4);
print(q[rear-1]);
return 0;
}