acwing 844 走迷宫 (bfs)

题面

在这里插入图片描述

题解

在这里插入图片描述

一般对于求所能到达的最短路径,都是用BFS来做,因为BFS是逐层遍历,当找到结果时,一定是距离最小的,BFS模板一般是用队列来做,然后将开始的点放入队列,然后开始找离起点距离最近的点,将其放入队列,循环即可。

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

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

int n, m;
int g[N][N], d[N][N];
int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, -1, 1};

int bfs() {

    memset(d, -1, sizeof d);
    PII q[N*N];
    int hh = 0, tt = -1;
    q[++tt] = {0, 0};
    d[0][0] = 0;
    while (hh <= tt) {
        auto t = q[hh++];
        for (int i = 0; i < 4; i++) {
            int x = t.first + dx[i], y = t.second + dy[i];
            if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) {
                d[x][y] = d[t.first][t.second] + 1;
                q[++tt] = {x, y};
            }
        }
    }

    return d[n - 1][m - 1];

}


int main() {

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    cin >> n >> m;

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

    cout << bfs() << endl;

    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值