a713中等三維六方向BFS最短路

CPE:Dungeon Master (UVa 532)

用層、列、欄座標找出每分鐘一步的最短逃脫時間。

解題思路

每個可走格子是一個頂點,與上、下、前、後、左、右六格連邊,邊權都為1。由S開始BFS,距離設0;取出某格時將尚未拜訪的合法鄰格設成距離加1並入列。BFS按距離逐層處理,所以第一次到達E就是最少分鐘數。

用三維距離陣列的−1表示未走訪,入列立刻改值避免重複。檢查三個維度邊界後才讀格子,#不可走,S與E都可走。分詞讀入各地圖行可忽略層間空白行,讀到0 0 0停止。可達輸出Escaped in x minute(s).,否則Trapped!。

Step-by-step animation

示意:兩層各1×2,上層S.,下層#E

回報動畫錯誤
步驟 1 / 3

起點

S=(0,0,0),距離0,下方是牆。

(0,0,0):0
(0,0,1):-1
(1,0,1):-1
queue長度
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <array>
using namespace std;
int main() {
    int l, r, c;
    while (cin >> l >> r >> c && (l || r || c)) {
        vector<vector<string>> a(l, vector<string>(r));
        array<int, 3> start{}, end{};
        for (int z = 0; z < l; z++)
            for (int x = 0; x < r; x++) {
                cin >> a[z][x];
                for (int y = 0; y < c; y++) {
                    if (a[z][x][y] == 'S')
                        start = {z, x, y};
                    if (a[z][x][y] == 'E')
                        end = {z, x, y};
                }
            }
        vector<vector<vector<int>>> dist(l, vector<vector<int>>(r, vector<int>(c, -1)));
        queue<array<int, 3>> q;
        q.push(start);
        dist[start[0]][start[1]][start[2]] = 0;
        int dz[] = {-1, 1, 0, 0, 0, 0}, dx[] = {0, 0, -1, 1, 0, 0}, dy[] = {0, 0, 0, 0, -1, 1};
        while (!q.empty()) {
            auto u = q.front();
            q.pop();
            for (int d = 0; d < 6; d++) {
                int z = u[0] + dz[d], x = u[1] + dx[d], y = u[2] + dy[d];
                if (z < 0 || z >= l || x < 0 || x >= r || y < 0 || y >= c || a[z][x][y] == '#' ||
                    dist[z][x][y] >= 0)
                    continue;
                dist[z][x][y] = dist[u[0]][u[1]][u[2]] + 1;
                q.push({z, x, y});
            }
        }
        int answer = dist[end[0]][end[1]][end[2]];
        if (answer < 0)
            cout << "Trapped!\n";
        else
            cout << "Escaped in " << answer << " minute(s).\n";
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多