题目链接: [迷宫问题]
大致题意:
一个5 × 5的二维数组,1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求找出并输出从左上角到右下角的最短路线
解题思路:
最短路线,肯定bfs,定义一个结构体存路线,当前点存上一个点的路线,最后递归输出
AC代码:
#include<iostream>
#include<queue>
#include<algorithm>
#include<cstdio>
using namespace std;
const int N = 200;
int mp[N][N];
int vis[N][N];
int fx[][2] = { 1,0,0,1,-1,0,0,-1 };
struct node {
int x, y;
};
queue<node>p;
node q[N][N];
bool bfs() {
node tmp = { 1,1 };p.push(tmp);
while (!p.empty()) {
tmp = p.front();p.pop();
int dx, dy;
for (int i = 0; i < 4; ++i) {
dx = tmp.x + fx[i][0];dy = tmp.y + fx[i][1];
if (dx == 5 && dy == 5) {
q[dx][dy] = tmp;
return 1;
}
if (mp[dx][dy] == 1 || vis[dx][dy] == 1 || dx < 1 || dx>5 || dy < 1 || dy>5)continue;
vis[dx][dy] = 1;
node f = { dx,dy };p.push(f);
q[dx][dy] = tmp;
}
}
return 0;
}
void show(int i, int j) {
if (i == 1 && j == 1) {
printf("(%d, %d)\n", i - 1, j - 1);
return;
}
node tmp = q[i][j];
show(tmp.x, tmp.y);
printf("(%d, %d)\n", i - 1, j - 1);
}
int main() {
for (int i = 1; i <= 5; ++i) {
for (int j = 1; j <= 5; ++j) {
cin >> mp[i][j];
}
}
bfs();
show(5, 5);
return 0;
}