【笔记】★迷宫最短路径——BFS

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

// 定义方向数组,分别表示下、左、右、上
const int dx[] = {1, 0, 0, -1};
const int dy[] = {0, -1, 1, 0};

// BFS 函数,返回最短路径长度,如果不存在路径则返回 -1
int bfs(vector<vector<int>>& maze, pair<int, int> start, pair<int, int> end) {
    int rows = maze.size();
    int cols = maze[0].size();
    vector<vector<bool>> visited(rows, vector<bool>(cols, false));  // 记录节点是否已访问
    vector<vector<int>> dist(rows, vector<int>(cols, 0));  // 记录节点到起点的距离

    queue<pair<int, int>> q;
    q.push(start);
    visited[start.first][start.second] = true;

    while (!q.empty()) {
        pair<int, int> cur = q.front();
        q.pop();

        // 检查是否到达终点
        if (cur == end) {
            return dist[cur.first][cur.second];
        }

        // 扩展邻居节点
        for (int i = 0; i < 4; ++i) {
            int newX = cur.first + dx[i];
            int newY = cur.second + dy[i];

            // 检查新节点是否在迷宫范围内,可通行且未被访问
            if (newX >= 0 && newX < rows && newY >= 0 && newY < cols && maze[newX][newY] == 0 &&!visited[newX][newY]) {
                q.push({newX, newY});
                visited[newX][newY] = true;
                dist[newX][newY] = dist[cur.first][cur.second] + 1;
            }
        }
    }

    // 如果队列为空仍未找到终点,则不存在路径
    return -1;
}

int main() {
    vector<vector<int>> maze = {
        {0, 1, 0, 0},
        {0, 0, 1, 0},
        {0, 0, 0, 0},
        {0, 0, 1, 0}
    };
    pair<int, int> start = {0, 0};
    pair<int, int> end = {3, 3};

    int shortestDist = bfs(maze, start, end);
    if (shortestDist != -1) {
        cout << "最短路径长度为: " << shortestDist << endl;
    } else {
        cout << "不存在从起点到终点的路径" << endl;
    }

    return 0;
}
posted @ 2025-03-29 20:41  量子流浪猫  阅读(32)  评论(0)    收藏  举报