J – 迷宫问题
题目:
定义一个二维数组:
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<bits/stdc++.h>
#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
struct Node
{
int x;
int y;
}b[30][30];
int vis[5][5];//用于标记点的新旧
int a[5][5];//迷宫
int direction[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
void print(int i,int j)
{
if(i == 0 && j == 0)
{
cout << "(0, 0)" << endl;
return;
}
print(b[i][j].x,b[i][j].y);
cout << "(" << i << ", " << j << ")" << endl;
}
void bfs(int xx,int yy)
{
queue<Node> q;
Node pre;
pre.x = xx;
pre.y = yy;
q.push(pre);
while(!q.empty())
{
pre = q.front();//pre代表前一个点
q.pop();
for(int i = 0;i < 4;i++)
{
Node temp;//定义一个暂时的点
temp.x = pre.x + direction[i][0];
temp.y = pre.y + direction[i][1];//当前的结点等于上一个结点移动之后的位置
if(temp.x >= 0 && temp.x < 5 && temp.y >= 0 && temp.y < 5 && a[temp.x][temp.y] == 0)
{
a[temp.x][temp.y] = 1;//将这个点设置为旧点
q.push(temp);
b[temp.x][temp.y] = pre;//记录前一个点
pre = temp;//将前一个点替换为现在的点
}
}
}
}
int main()
{
for(int i = 0;i < 5;i++)
{
for(int j = 0;j < 5;j++) scanf("%d",&a[i][j]);
}
bfs(0,0);
print(4,4);
return 0;
}
这道题是一道经典的BFS题,找到最短的路径并不难,难的是如何把这条最短的路线给保存下来。
具体的方法是:定义一个二维结构体数组。每次找到一个新的满足条件的点,就把这个点的横纵坐标保存下来,并且存储前一个点的横纵坐标,随后把这个点设置为1(也就是把这个点设置为墙壁),最后将前一个点更新当前点。
打印路线的时候使用递归就可以了,从终点开始往它前一个点搜寻,一直搜寻到起点,随后按照顺序打印即可。