题目描述
PIPI定义了一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,请找出从左上角到右下角的最短路线。
输入
仅一组测试用例。
一个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
样例输出
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
思路:要记录每个位置前一个位置的值,bfs结束之后,从终点回溯到起点
#include<bits/stdc++.h>
using namespace std;
int maze[6][6];
bool vis[6][6];
int dir[][2]={0,1,0,-1,1,0,-1,0};
struct node
{
int x,y;
};
node pre[10][10];
bool judge(int x,int y)
{
if(x<0||x>=5||y<0||y>=5) return false;
if(maze[x][y]||vis[x][y]) return false;
return true;
}
void bfs(int sx,int sy)
{
queue<node>q;
node Node;
Node.x=sx,Node.y=sy;
vis[sx][sy]=1;
q.push(Node);
while(q.size())
{
node top=q.front();q.pop();
if(top.x==4&&top.y==4)
return;
for(int i=0;i<4;i++)
{
int newx=top.x+dir[i][0];
int newy=top.y+dir[i][1];
if(judge(newx,newy))
{
Node.x=newx;
Node.y=newy;
q.push(Node);
pre[Node.x][Node.y]=top; ///pre数组记录每个位置的前一个结点
vis[newx][newy]=1;
}
}
}
}
void print(node cur)
{
if(cur.x==0&&cur.y==0){
printf("(0, 0)\n");
return;
}
print(pre[cur.x][cur.y]); ///从末尾的位置回溯到起点 逆序输出
printf("(%d, %d)\n",cur.x,cur.y);
}
main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
scanf("%d",&maze[i][j]);
bfs(0,0);
node ed;
ed.x=4,ed.y=4;
print(ed);
}