a322中等立體連通分量・六方向 flood fill

TOI 2019/03 潛力組:尋找蜂后

按共面相鄰的空間解讀,找出最大的 0 連通分量,並揭露原題方向規格的限制。

前往題目練習 →回報教學錯誤V=LWH≤135³=2460375,六方向搜尋時間 O(V),輸入與顯式堆疊空間 O(V)。Python 堆疊使用 array('I')。

解題思路

本題原稿沒有逐一列出方向,只有立體圖示;以下採格子共面相鄰的六方向(±x、±y、±z),這個解讀符合兩組官方範例,但不能宣稱是原文明訂的方向清單。把每層排成 W 列、每列 L 格,索引為 z×LW+y×L+x。左右、前後、上下分別差 1、L、LW,仍須檢查各自座標邊界,不能讓列尾接到下一列開頭。

掃描全部格子,每遇到尚未拜訪的 0 就以顯式堆疊展開整個連通分量,將發現的格子立即改為 1,避免重複入堆疊。每次展開完成後更新最大格數。每個空格只被計數一次,牆不進入搜尋;全部是牆時答案為 0。最大體積超過兩百萬格,不能用逐格遞迴。

Step-by-step animation

較小示例:L=2、W=2、H=1,字串 0010

回報動畫錯誤
步驟 1 / 3

從索引 0 出發

空格 (0,0,0) 入堆疊並立刻標記。

0已訪
1空
2牆
3空
分量大小
0
堆疊
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int l, w, h;
    cin >> l >> w >> h;
    string grid, part;
    int layer = l * w, volume = layer * h;
    while ((int)grid.size() < volume && cin >> part)
        grid += part;
    vector<int> stack;
    int answer = 0;
    auto visit = [&](int p) {
        if (grid[p] == '0') {
            grid[p] = '1';
            stack.push_back(p);
        }
    };
    for (int start = 0; start < volume; ++start)
        if (grid[start] == '0') {
            visit(start);
            int count = 0;
            while (!stack.empty()) {
                int p = stack.back();
                stack.pop_back();
                ++count;
                int x = p % l, y = (p / l) % w, z = p / layer;
                if (x)
                    visit(p - 1);
                if (x + 1 < l)
                    visit(p + 1);
                if (y)
                    visit(p - l);
                if (y + 1 < w)
                    visit(p + l);
                if (z)
                    visit(p - layer);
                if (z + 1 < h)
                    visit(p + layer);
            }
            answer = max(answer, count);
        }
    cout << answer << '\n';
}

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

更多