定义一个二维数组:
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)
第一次 Presentation Error,又一次想当然输出格式,一定要直接复制格式!空格或者换行之类
因为到终点前无法确认最短路径,只能在抵达终点后一步步回溯,这就需要之前每一步走时记录上一个点;这里用pre记录上一个点在queue里的排列位置;queue绝不及25个点;
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
struct Node
{
int x,y,pre;
};
Node q[25],pt;
stack<Node>s;
int k=0,st=0,m[5][5],xx[4]={0,1,0,-1},yy[4]={1,0,-1,0},vis[5][5];//k=队列最后一个点在队列中的位置,st=当前步数
void bfs()
{
int xt,yt;
while(pt.x!=4||pt.y!=4)
{
for(int i=0;i<4;i++)
{
xt=pt.x+xx[i];yt=pt.y+yy[i];
if(xt>=0&&xt<5&&yt>=0&&yt<5&&m[xt][yt]!=1&&!vis[xt][yt])
{
vis[xt][yt]=1;
q[++k].x=xt;q[k].y=yt;q[k].pre=st;
}
}
pt=q[++st];
}
while(pt.x!=0||pt.y!=0)
{
s.push(pt);
pt=q[pt.pre];
}
s.push(pt);
while(!s.empty())
{
pt=s.top();
s.pop();
printf("(%d, %d)\n",pt.x,pt.y);
}
}
int main()
{
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
scanf("%d",&m[i][j]);
}
}
pt.x=0;pt.y=0;
q[0].x=0;q[0].y=0;q[0].pre=-1;
bfs();
return 0;
}