BFS

走迷宫

知识点

  • 队列:先进先出
queue<int> numbers;

解题思路

  • 初始化g[N][N], d[N][N]
    • g[N][N]:用来记录迷宫地图
    • d[N][N]:用来记录该点距离原点的距离
  • 使用bfs对每个节点进行遍历
  • 使用queue存储节点,由于先进先出的特性,我们会将距离原点距离的相同的点一次性都遍历完成,由此实现bfs
  • 对单一节点,4个方向都要进行遍历
  • 遍历结束后,返回d[n - 1][m - 1]

实现代码

#include <bits/stdc++.h>

using namespace std;

typedef pair<int, int> PII;

const int N = 110;

int g[N][N],  d[N][N];
int n, m;

int bfs(){
    queue<PII> q;

    memset(d, -1, sizeof d);

    d[0][0] = 0;
    q.push({0, 0});
    vector<PII> directions = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};


    while(q.size()){
        auto t = q.front();
        q.pop();



        for(int i = 0; i < 4; i ++){
            int x = t.first + directions[i].first, y = t.second + directions[i].second;
            if(x >= 0 && x < n && y >= 0 && y < m && d[x][y] == -1 && g[x][y] == 0){
                q.push({x, y});
                d[x][y] = d[t.first][t.second] + 1;
            }
        }
    }


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

int main(){
    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;
}



Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • Google Gemini updates: Flash 1.5, Gemma 2 and Project Astra
  • Displaying External Posts on Your al-folio Blog
  • 强化学习导论
  • 企业项目实训
  • 面试总结