迷宫问题(程序设计与算法(二)第10周测验-bfs+记录路径)
judge:迷宫问题
总时间限制: 1000ms
内存限制: 65536kB
描述
定义一个二维数组:
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)
思路
广搜过程中维护一个链表用来记录路径
代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <map>
#define m_p make_pair
#define maxn 35
#define maxm 505
#define _for(i, a) for(LL i = 0; i < (a); i++)
#define _rep(i, a, b) for(LL i = (a); i <= (b); i++)
#define outval(a) cout<<#a<<": "<<a<<"\n"
using namespace std;
typedef long long LL;
const LL MAXN = 110;
const LL inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-10;
struct poi {
int x, y, pre, pos;
poi() {}
poi(int x, int y, int pos) :x(x), y(y), pos(pos) {}
poi(int x, int y, int pre, int pos) :x(x), y(y), pre(pre), pos(pos) {}
};
vector<poi> vec, ans;
bool a[maxn][maxn], used[maxn][maxn];
int dir[4][2] = { 0, 1, 1, 0, 0, -1, -1, 0 };
void init() {
memset(used, 0, sizeof(used));
vec.clear();
ans.clear();
}
void bfs() {
queue<poi> Q;
Q.push(poi(0, 0, 0));
vec.push_back(poi(0, 0, -1, vec.size()));
used[0][0] = 1;
while (Q.size()) {
poi c = Q.front();
Q.pop();
if (c.x == 4 && c.y == 4) {
for (int i = c.pos; ~i; i = vec[i].pre) {
ans.push_back(vec[i]);
}
return;
}
_for(i, 4) {
int x = c.x + dir[i][0];
int y = c.y + dir[i][1];
if (x >= 0 && x < 5 && y >= 0 && y < 5 && !used[x][y] && !a[x][y]) {
Q.push(poi(x, y, vec.size()));
vec.push_back(poi(x, y, c.pos, vec.size()));
used[x][y] = 1;
}
}
}
}
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//freopen("in.txt", "r", stdin);
init();
_for(i, 5) {
_for(j, 5) {
cin >> a[i][j];
}
}
bfs();
for(int i = ans.size() - 1; i >= 0; i--) {
cout << "(" << ans[i].x << ", " << ans[i].y << ")\n";
}
return 0;
}
/*
*/