解題思路
按列優先掃描,遇到未訪問的 1 就開一次 BFS;起點距離標為 1。
每次走上下左右的未訪問黑點,標成當前距離加一。BFS 保證第一次發現的就是最短距離,因此最遠距離正是同步擴張所需層數。
本次佇列清空後,一整個四連通分量已處理;記錄最大層數,繼續掃描。輸出分量數與各自層數。
時間 O(n²),圖、已訪問狀態與佇列 O(n²)。
Step-by-step animation
逐連通分量的廣度優先搜尋|2×2 圖只有左上與右下為黑,先選左上。
步驟 1 / 3
掃描
2×2 圖只有左上與右下為黑,先選左上。
1
0
0
1
- 層數
- 1
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<string> a(n);
for (auto &s : a)
cin >> s;
vector<int> ans;
int dr[] = {1, -1, 0, 0}, dc[] = {0, 0, 1, -1};
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++)
if (a[r][c] == '1') {
queue<array<int, 3>> q;
q.push({r, c, 1});
a[r][c] = '0';
int best = 1;
while (q.size()) {
auto t = q.front();
q.pop();
best = max(best, t[2]);
for (int k = 0; k < 4; k++) {
int x = t[0] + dr[k], y = t[1] + dc[k];
if (x >= 0 && x < n && y >= 0 && y < n && a[x][y] == '1') {
a[x][y] = '0';
q.push({x, y, t[2] + 1});
}
}
}
ans.push_back(best);
}
cout << ans.size() << "\n";
for (int x : ans)
cout << x << "\n";
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。