返回主页

二维矩阵 BFS 搜索模板

BFS 搜索二维矩阵中从 (1, 1) 到 (n, m) 的最短路径长度

算法模板发布于 2026/08/22#bfs#最短路径
C++41 行982 Bytes
下载文件
#include <bits/stdc++.h>
using namespace std;

int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

const int N = 105;          // 根据题目数据范围调整
bool vis[N][N];
int step[N][N], n, m;

struct point { int x, y; };

void bfs(int x, int y) {
    vis[x][y] = 1;           // 标记起点
    queue<point> q;
    q.push({x, y});

    while (!q.empty()) {
        point u = q.front(); q.pop();

        for (int i = 0; i < 4; i++) {
            int nx = u.x + dx[i], ny = u.y + dy[i];
            if (nx < 1 || nx > n || ny < 1 || ny > m || vis[nx][ny])
                continue;

            step[nx][ny] = step[u.x][u.y] + 1;
            if (nx == n && ny == m) return;  // 到达终点提前返回
            vis[nx][ny] = 1;
            q.push({nx, ny});
        }
    }
}

int main() {
    cin >> n >> m;
    // 如果有障碍物,可以预先将 vis[a][b] 置为 1

    bfs(1, 1);
    cout << step[n][m];   // 如果不可达,step[n][m] 仍为 0
    return 0;
}