#35978: C++答案(附註解)


samlin961112@gmail.com (林哲甫)

學校 : 新北市私立南山高級中學
編號 : 220506
來源 : [219.70.213.92]
最後登入時間 :
2024-04-28 22:43:43
a982. 迷宮問題#1 | From: [219.70.213.92] | 發表日期 : 2023-06-27 22:27

#include <bits/stdc++.h>
using namespace std;

int n;
vector<vector<int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};  // 四个方向的偏移量

int bfs(vector<vector<char>>& map) {
    vector<vector<int>> ans(n, vector<int>(n, INT_MAX));  // 记录最短路径长度的数组
    queue<pair<int, int>> q;  // 广度优先搜索的队列
    ans[1][1] = 0;  // 起点到自身的路径长度为0
    q.push({1, 1});  // 将起点加入队列

    while (!q.empty()) {
        pair<int, int> curr = q.front();  // 当前位置
        q.pop();
        int x = curr.first;  // 当前位置的横坐标
        int y = curr.second;  // 当前位置的纵坐标

        if (x == n - 2 && y == n - 2) {  // 如果到达终点
            return ans[x][y];  // 返回最短路径长度
        }

        // 遍历四个方向
        for (auto& dir : dirs) {
            int nx = x + dir[0];  // 计算下一个位置的横坐标
            int ny = y + dir[1];  // 计算下一个位置的纵坐标

            // 判断下一个位置是否合法,是否为可通行的路,并且之前没有访问过
            if (nx >= 0 && nx < n && ny >= 0 && ny < n && map[nx][ny] != '#' && ans[nx][ny] == INT_MAX) {
                ans[nx][ny] = ans[x][y] + 1;  // 更新最短路径长度
                q.push({nx, ny});  // 将下一个位置加入队列
            }
        }
    }

    return -1;  // 没有找到路径
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> n;
    vector<vector<char>> map(n, vector<char>(n));  // 迷宫地图
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> map[i][j];  // 读取迷宫地图
        }
    }

    int shortestPath = bfs(map);  // 使用广度优先搜索计算最短路径长度
    if (shortestPath == -1) {
        cout << "No solution!";  // 没有找到路径
    } else {
        cout << shortestPath;  // 输出最短路径长度
    }

    return 0;
}

 
ZeroJudge Forum