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;
}



猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/114364186