迷宫问题 |
---|
题意: 在一个5*5的迷宫中,数字0表示为可通过的路,数字1表示为不可通过的墙。问从左上角走到右下角的最短路线,并且输出路径。(题目保证只有一组解,所以不用考虑字典序啥的)
题解: 据说,题目真的只有一组解,你只要复制样例中的输出然后提交就能过。 虽然但是,还是要正儿八经做题的,输出路径最近常干了,甚至自己都已经出过一道输出路径的BFS题目了。添加两个pre数组记录前驱节点的坐标,最后借助栈从终点往起点递推,存入所有经过点,再输出出来即可。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
int G[6][6];
int dir[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int pre_x[6][6];
int pre_y[6][6];
struct node{
int x, y;
node(){}
node(int x, int y): x(x), y(y) {}
};
inline bool check(node u) {
if(u.x < 1 || u.x > 5 || u.y < 1 || u.y > 5) return false;
if(G[u.x][u.y] == 1) return false;
return true;
}
void print_path() {
stack<node> St;
St.push(node(5, 5));
while(1) {
node u = St.top();
node v;
v.x = pre_x[u.x][u.y];
v.y = pre_y[u.x][u.y];
St.push(v);
if(v.x == 1 && v.y == 1) break;
}
while(!St.empty()) {
node u = St.top(); St.pop();
printf("(%d, %d)\n", u.x - 1, u.y - 1);
}
}
void BFS() {
queue<node> Q;
Q.push(node(1, 1));
G[1][1] = 1;
while(!Q.empty()) {
node u = Q.front(); Q.pop();
if(u.x == 5 && u.y == 5) {
print_path();
return ;
}
for(int i = 0; i < 4; i++) {
node v = u;
v.x += dir[i][0], v.y += dir[i][1];
if(check(v)) {
pre_x[v.x][v.y] = u.x;
pre_y[v.x][v.y] = u.y;
G[v.x][v.y] = 1;
Q.push(v);
}
}
}
}
int main() {
ios :: sync_with_stdio(false); cin.tie(0); cout.tie(0);
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= 5; j++) {
cin >> G[i][j];
}
}
BFS();
return 0;
}