迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
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)
思路:
先看题目数据范围,是一个二维5*5的数组,数据较小;要找到一个最短路径从左上角的 0 走到右下角的 0,这道题有一个性质:相邻点的转移只花费1的代价,而bfs便可以在这种条件下解决最短性质问题 ,这样一层一层扩展,可以保证你选择的每一步都是最优步,而且我们知道,bfs要用到队列先进先出这一特征,(将每一点处可选择的方向作为子树,这样逐渐加深层次,知道找到终点)。并且,在这个路上,我们每次都需要一个pre[ ]数组来记录这一点的上一点,以方便回溯。回溯时要用到栈这一数据结构,因为我们需要先从终点推回起点,再重新输出路径。
AC代码如下:
#include <iostream>
#include <cstdio>
#include <queue>
#include <stack>
#include <string.h>
using namespace std;
const int maxn = 200;
struct Node{
int x, y;
}st, en, out, in;
// 本题不需要设置vis数组,题目中的0和1就可以该表是否走过
int mapp[maxn][maxn]; // 构造地图
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
Node pre[maxn][maxn]; // 每一个点的pre数组包括x和y
bool check(int x, int y){
if(x >= 0 && y >= 0 && x < 5 && y < 5 && mapp[x][y] == 0)
return 1;
return 0;
}
queue <Node> q;
stack <Node> s;
void bfs(){
while(!q.empty()) // 保证初始栈为空
q.pop();
q.push(st);
while(!q.empty()){
out = q.front(); // out 代表队头将要出去的点
q.pop();
if(out.x == en.x && out.y == en.y){
while(en.x != st.x || en.y != st.y){ // *****注意这里是||,必须两者不全等时压栈 ****
s.push(en); // 将这个点压入栈
en = pre[en.x][en.y]; // 利用pre[]数组保存的上一个点的坐标来回溯
} // pre[]和out一样是out类型的,可以等价
s.push(st); // 最后将起点压入队列
while(!s.empty()){
printf("(%d, %d)\n", s.top().x, s.top().y);
s.pop();
}
return;
}
for(int i = 0; i < 5; i++){
in.x = dx[i] + out.x;
in.y = dy[i] + out.y;
if(check(in.x, in.y)){
mapp[in.x][in.y] = 1;
q.push(in); // 将这个曾未走过的点压入队列
pre[in.x][in.y] = out; // pre[]和out一样是out类型的,可以等价
}
}
}
}
int main(){
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
scanf("%d", &mapp[i][j]);
st.x = 0;
st.y = 0;
en.x = 4;
en.y = 4;
bfs();
return 0;
}