定义一个二维数组:
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>
#include<cstring>
#include<iostream>
using namespace std;
int a[5][5];
bool vis[5][5];
typedef struct
{
int x,y,t;
short l[30];
}N;
N s,e;
int d[4][2]={{0,-1},{0,1},{-1,0},{1,0}};
bool judge(int x,int y)
{
if(x<0||x>=5||y<0||y>=5||vis[x][y]||a[x][y])
return true;
else
return false;
}
N bfs()
{
queue<N>q;
s.x=0;s.y=0;s.t=0;
vis[s.x][s.y]=true;
q.push(s);
while(q.size())
{
s=q.front();
q.pop();
if(s.x==4&&s.y==4)
return s;
for(int i=0;i<4;i++)
{
int xx=s.x+d[i][0],yy=s.y+d[i][1];
if(judge(xx,yy))
continue;
e=s;
e.x=xx;
e.y=yy;
e.t=s.t+1;
e.l[s.t]=i;
q.push(e);
}
}
return s;
}
int main()
{
int i;
for(i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>a[i][j];
memset(vis,0,sizeof(vis));
N ans=bfs();
int x=0,y=0;
for(i=0;i<=ans.t;i++)
{
cout<<"("<<x<<", "<<y<<")"<<endl;
x+=d[ans.l[i]][0];
y+=d[ans.l[i]][1];
}
return 0;
}