【题解】 走迷宫(BFS)

https://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64?tpId=308&tqId=40477&ru=/exam/oj
在这里插入图片描述

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int m, n, x1, y1, x2, y2;

vector<vector<int>> dist; // 用来标记走了多少步数
vector<vector<char>> bords; //
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};


int bfs() {
    queue<pair<int, int>> q;
    q.push({x1, y1});
    dist[x1][y1] = 0;

    while (q.size()) {
        auto[a, b] = q.front();
        q.pop();
        for (int i = 0; i < 4; ++i) {
            int x = a + dx[i], y = b + dy[i];
            if (x >= 0 && x < m && y >= 0 && y < n
                    && bords[x][y] == '.' && dist[x][y] == -1) {
                q.push({x, y});
                dist[x][y] = dist[a][b] + 1;
                if (x == x2 && y == y2) return dist[x2][y2];
            }
        }
    }
    return -1;
}


int main() {

    cin >> m >> n >> x1 >> y1 >> x2 >> y2;
    --x1;
    --y1;
    --x2;
    --y2;
    dist.assign(m, vector<int>(n, -1));
    bords.assign(m, vector<char>(n, 0));
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            cin >> bords[i][j];
        }
    }

    cout << bfs() << endl;

    return 0;
}
// 64 位输出请用 printf("%lld")
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Q_hd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值