牛客华为机试 HJ43 迷宫问题

写的宽搜找最短路径,额额,没想到其实直接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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值