3984.迷宫问题
题目链接-3984.迷宫问题
Description
定义一个二维数组:
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)
解题思路
b f s bfs bfs
- 因为要输出最短路径,用STL里的queue无法保留最短路径,所以我们可以用结构体数组模拟队列,以bg和ed为头尾指针
- 我们可以用结构体中的 x x x, y y y来记录路径中点的坐标, z z z来记录每个点的前驱节点
- 其他的就套bfs的板子,输出时我们只需用递归逆序输出即可
- 坑点:注意输出格式,逗号后面有个空格
- 具体操作见代码
附上代码
#include<iostream>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
char maze[5][5];
bool vis[5][5];
int way[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
struct node{
int x,y,z;
}a[100];
void print(int bg){
while(a[bg].z!=-1){//如果z不等于-1,说明该点有前驱节点
print(a[bg].z);
cout<<"("<<a[bg].x<<", "<<a[bg].y<<")"<<endl;
return ;
}
cout<<"(0, 0)"<<endl;
}
void bfs(){
node temp;
int bg=0,ed=1;
a[0].x=0;a[0].y=0;a[0].z=-1;//初始化
vis[0][0]=1;
while(bg<ed){
if(a[bg].x==4&&a[bg].y==4){
print(bg);
return ;
}
for(int i=0;i<4;i++){
temp.x=a[bg].x+way[i][0];
temp.y=a[bg].y+way[i][1];
temp.z=bg;//记录前驱节点
if(temp.x<0||temp.x>4||temp.y<0||temp.y>4||maze[temp.x][temp.y]=='1'||vis[temp.x][temp.y])
continue;
vis[temp.x][temp.y]=1;
a[ed]=temp;
ed++;
}
bg++;
}
}
int main(){
memset(vis,0,sizeof(vis));
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
cin>>maze[i][j];
}
}
bfs();
return 0;
}