a630中等左右環接地圖的連通塊

CPE:Continents (UVa 11094)

先排除國王大陸,再統計其他同字元大陸的最大面積。

前往題目練習 →回報教學錯誤每組 O(MN) 時間、O(MN) 空間。

解題思路

國王所在格的字元定義陸地,不能假設一定是 l。先從國王位置做洪水填充,將其整塊陸地標為已訪;再掃描全圖,每遇到未訪陸地就填充並計數,取最大的分量。

上下座標必須落在 [0,M),左右則以 (c±1+N)%N 處理,所以同列兩側可以相連。入堆疊時標記,每個陸地只計一次;若剩下沒有其他大陸,初始最大值 0 即答案。輸入組間有空白行,以 token 讀取方格和座標可自然略過,直到 EOF。

Step-by-step animation

示意:三列 lwl/www/llw,國王 (0,0)

回報動畫錯誤
步驟 1 / 3

辨認陸地

國王字元 l,第一列左右兩格透過環接相連。

lwl
www
llw
國王大陸大小
2

Reference solution

回報程式錯誤

完整程式

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
    int m, n;
    while (cin >> m >> n) {
        vector<string> g(m);
        for (auto &s : g)
            cin >> s;
        int x, y;
        cin >> x >> y;
        char land = g[x][y];
        vector<vector<bool>> seen(m, vector<bool>(n));
        auto flood = [&](int r, int c) {
            vector<pair<int, int>> stack = {{r, c}};
            seen[r][c] = true;
            int count = 0;
            while (!stack.empty()) {
                auto [a, b] = stack.back();
                stack.pop_back();
                ++count;
                int rr[] = {a - 1, a + 1, a, a}, cc[] = {b, b, (b + n - 1) % n, (b + 1) % n};
                for (int k = 0; k < 4; ++k) {
                    int u = rr[k], v = cc[k];
                    if (u >= 0 && u < m && !seen[u][v] && g[u][v] == land) {
                        seen[u][v] = true;
                        stack.push_back({u, v});
                    }
                }
            }
            return count;
        };
        flood(x, y);
        int answer = 0;
        for (int r = 0; r < m; ++r)
            for (int c = 0; c < n; ++c)
                if (g[r][c] == land && !seen[r][c])
                    answer = max(answer, flood(r, c));
        cout << answer << '\n';
    }
}

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

更多