题目:
定义一个二维数组:
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<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
int map[5][5];
int vis[5][5];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
int x,y,step,l[50];
};//通过记录方向来记录路径
node a;
int judge(int x,int y)
{
if(x<0||x>=5||y<0||y>=5||vis[x][y]||(map[x][y]==1))
return 0;
else return 1;
}
int BFS()
{
queue<node>q;
node t,next;
t.x=0;
t.y=0;
t.step=0;
vis[0][0]=1;
q.push(t);
while(!q.empty())
{
a=q.front();
q.pop();
if(a.x==4&&a.y==4)
return a.step;
for(int i=0;i<4;i++)
{
next=a;
next.x=a.x+dir[i][0];
next.y=a.y+dir[i][1];
if(judge(next.x,next.y))
{
next.step++;
vis[next.x][next.y]=1;
next.l[a.step]=i;
q.push(next);
}
}
}
return -1;
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
{
cin>>map[i][j];
}
int num=BFS();
printf("(0, 0)\n");
int x=0,y=0;
for(int i=0;i<num;i++)
{
x+=dir[a.l[i]][0];
y+=dir[a.l[i]][1];
printf("(%d, %d)\n",x,y);
}
return 0;
}