a626困難多源火勢 BFS 與帶時間限制的逃生 BFS

CPE:Fire! (UVa 11624)

先算每格著火時間,再找 Joe 能安全離開的最短路。

前往題目練習 →回報教學錯誤時間 O(RC),空間 O(RC)。

解題思路

把所有 F 同時放進佇列,以多源 BFS 求 fire[v],即每格最早起火分鐘;牆不可通行,永遠不到的格子時間為無限。這一步把持續變動的火勢轉成靜態的格子截止時間。

再從 J 做 BFS,走到鄰格 v 的時間 t+1 必須嚴格小於 fire[v],同分鐘到達不安全。若目前位在邊界,下一步走出格外便完成,所以答案是目前時間加一,起點在邊界時為 1。BFS 首次安全到達某格就是最早時間,不需再次入列。Python 以一維編號及緊密整數陣列保存百萬格火勢時間,避免大量座標物件;無路可走印 IMPOSSIBLE。

Step-by-step animation

示意:3×3 空地,J=(1,1),F=(0,0)

回報動畫錯誤
步驟 1 / 3

火勢時間

火抵各列時間為 0,1,2/1,2,3/2,3,4。

0 1 2
1 2 3
2 3 4
Joe 起始時間
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
int main() {
    int t;
    cin >> t;
    while (t--) {
        int r, c;
        cin >> r >> c;
        vector<string> g(r);
        for (auto &s : g)
            cin >> s;
        vector<int> fire(r * c, -1), time(r * c, -1);
        queue<int> q;
        int start = 0;
        for (int i = 0; i < r; ++i)
            for (int j = 0; j < c; ++j) {
                int v = i * c + j;
                if (g[i][j] == 'F') {
                    fire[v] = 0;
                    q.push(v);
                }
                if (g[i][j] == 'J')
                    start = v;
            }
        int dr[] = {-1, 1, 0, 0}, dc[] = {0, 0, -1, 1};
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            int x = u / c, y = u % c;
            for (int k = 0; k < 4; ++k) {
                int a = x + dr[k], b = y + dc[k];
                if (a < 0 || a >= r || b < 0 || b >= c || g[a][b] == '#')
                    continue;
                int v = a * c + b;
                if (fire[v] < 0) {
                    fire[v] = fire[u] + 1;
                    q.push(v);
                }
            }
        }
        q.push(start);
        time[start] = 0;
        int answer = -1;
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            int x = u / c, y = u % c;
            if (x == 0 || x == r - 1 || y == 0 || y == c - 1) {
                answer = time[u] + 1;
                break;
            }
            for (int k = 0; k < 4; ++k) {
                int a = x + dr[k], b = y + dc[k], v = a * c + b, nt = time[u] + 1;
                if (g[a][b] != '#' && time[v] < 0 && (fire[v] < 0 || nt < fire[v])) {
                    time[v] = nt;
                    q.push(v);
                }
            }
        }
        if (answer < 0)
            cout << "IMPOSSIBLE\n";
        else
            cout << answer << '\n';
    }
}

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

更多