题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int main() {
int n, m, num = 0;
int n2, m2;
int map0[10][10];
pair<int, int> map1[10][10];
queue<pair<int, int>> q;
q.push({ 0,0 });
vector<pair<int, int>> ans, move = { {0,1},{0,-1},{-1,0},{1,0} };
cin >> n >> m;
n2 = n - 1;
m2 = m - 1;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> map0[i][j];
map0[0][0] = 1;
while (!q.empty()) {
for (int i = q.size(); i > 0; i--) {
auto it = q.front();
q.pop();
for (auto x : move) {
int n1 = it.first + x.first;
int m1 = it.second + x.second;
if (n1 >= 0 && n1 < n && m1 >= 0 && m1 < m && map0[n1][m1] == 0) {
q.push({ n1,m1 });
map0[n1][m1] = 1;
map1[n1][m1] = it;
}
}
}
num++;
if (map0[n2][m2] == 1) break;
}
ans.push_back({n2,m2});
for (int i = 0; i < num; i++) {
n = map1[n2][m2].first;
m = map1[n2][m2].second;
n2 = n;
m2 = m;
ans.push_back({ n2,m2 });
}
for (int i = ans.size() - 1; i >= 0; i--)
cout << '(' << ans[i].first << ',' << ans[i].second << ')' << endl;
}
广度优先搜索,用一个数组来记录路径
查看18道真题和解析
