解題思路
求引爆所有地雷所需的最少飛彈數。
兩個3×3感測區有共同格,等價於地雷中心兩軸差都不超過2。地雷座標為整數,可直接查周圍5×5位置是否有另一顆。
將可連鎖地雷視為圖邊,從任一未處理地雷做堆疊走訪,能引爆整個連通分量。
不同分量無共同感測格,也不可能互相連鎖,因此每分量至少一發、一發也足夠,答案就是分量數。
Python期望時間 O(c),C++平衡樹 O(c log c),空間 O(c);不配置整張地圖。
Step-by-step animation
第二組公開範例的鏈狀連鎖
步驟 1 / 3
步驟 1
示例地雷(2,2)、(3,3)、(4,5)。
三顆地雷
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
string a, b;
int c;
cin >> a >> b >> c;
set<pair<int, int>> s;
while (c--) {
int x, y;
cin >> x >> y;
s.insert({x, y});
}
int ans = 0;
while (!s.empty()) {
auto p = *s.begin();
s.erase(s.begin());
vector<pair<int, int>> q{p};
ans++;
while (!q.empty()) {
auto [x, y] = q.back();
q.pop_back();
for (int i = -2; i <= 2; i++)
for (int j = -2; j <= 2; j++) {
auto it = s.find({x + i, y + j});
if (it != s.end()) {
q.push_back(*it);
s.erase(it);
}
}
}
}
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。