写的宽搜找最短路径,额额,没想到其实直接bfs就行了,题中说路径唯一,,太坑了
所以这题可以直接dfs,搞一个栈记录路径,最后逆序输出就行了
#include <iostream>
#include <queue>
#include <algorithm>
#include <stack>
#include <unordered_map>
using namespace std;
#define xx first
#define yy second
typedef pair<int, int> PII;
//注意哈希表key不能为pair,否则要自己写哈希函数
unordered_map<int, PII> path;
unordered_map<int, int> dist;
queue<PII> q;
// stack<PII> path;
int min_dist, m, n;
vector<vector<int>> arr;
PII trans_ordinate(int t) {
return {t / n, t - t / n * n};
}
int trans_val(int x, int y){
return x * n + y;//注意是乘列数
}
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1};
void bfs() {
dist[0] = 0;
while(q.size()){
auto t = q.front(); q.pop();
for(int i = 0; i < 4; i ++){
int x = t.xx + dx[i], y = t.yy + dy[i];
int val = trans_val(x, y), val2 = trans_val(t.xx, t.yy);
//如果坐标越界或者是障碍或者已经走过或者已经被选中过为下一条路
if(x < 0 || y < 0 || x >= m || y >= n || arr[x][y] || dist.count(val) || path.count(val)) continue;
dist[val] = dist[val2] + 1;
path[val] = {t.xx, t.yy};
q.push({x, y});
}
}
}
//递归输出路径
void output(int val){
if(path.count(val)){
int x = path[val].xx , y = path[val].yy;
int pre_point = trans_val(x, y);
output(pre_point);
}
auto point = trans_ordinate(val);
cout << '(' << point.xx << ',' << point.yy << ')' << endl;
}
int main() {
cin >> m >> n;
arr = vector(m, vector<int>(n));
for (int i = 0; i < m; i ++)
for (int j = 0; j < n; j ++)
cin >> arr[i][j];
q.push({0, 0});
bfs();
int res = trans_val(m - 1, n - 1);
output(res);
return 0;
}