acwing 1076 迷宫问题(最短路模型)

题面

在这里插入图片描述

题解(最短路模型)

迷宫问题+输出路径,因为每个点之间的距离都是1,所以用BFS搜索出来的结果就是最短的距离,我们新开一个数组,然后我们从终点开始最终搜索到起点,记录每个点的前一个点是从哪转移过来的,最后从(0,0)点遍历一遍即可

代码

#include<bits/stdc++.h>

using namespace std;
typedef pair<int, int> PII;
const int N = 1010;

int n;
int g[N][N];
PII q[N * N];
PII pre[N][N];
int dx[4] = {0, -1, 0, 1};
int dy[4] = {1, 0, -1, 0};

void bfs(int sx, int sy) {
    memset(pre, -1, sizeof pre);
    pre[sx][sy] = {0, 0};
    int hh = 0, tt = -1;
    q[++tt] = {sx, sy};
    while (hh <= tt) {
        PII t = q[hh++];
        int x = t.first, y = t.second;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                int nx = x + dx[i], ny = y + dy[i];
                if (nx < 0 || nx > n - 1 || ny < 0 || ny > n - 1) continue;
                if (pre[nx][ny].first != -1) continue;  //说明已经遍历过
                if (g[i][j]) continue;
                q[++tt] = {nx, ny};
                pre[nx][ny] = t;   //从后往前遍历,记录上一个点
            }
        }
    }
}


int main() {

    cin >> n;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> g[i][j];
        }
    }

    bfs(n - 1, n - 1);
    PII end = {0, 0};  //正向输出
    while (true) {
        cout << end.first << " " << end.second << endl;
        if (end.first == n - 1 && end.second == n - 1) break;
        end = pre[end.first][end.second];
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值