這題在學什麼
每個值為 5 的格先查看八鄰格,有另一個 5 就失靈,否則正常。
正常偵測器的八鄰格中,值為 1 的位置在 detected 矩陣標記為真。
最後走訪所有炸彈,按 detected 分為可找到與不可找到;原矩陣完全不修改。
Step-by-step animation
炸彈偵測器・先判失靈再標記
步驟 1 / 3
判定正常偵測器
(0,0) 與 (0,2) 相隔兩格,不在彼此八鄰格中。
5 0 5
0 1 0
1 0 1
- 正常偵測器
- 2
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int r, c;
cin >> r >> c;
vector<vector<int>> a(r, vector<int>(c));
for (auto &row : a)
for (int &x : row)
cin >> x;
vector<vector<bool>> seen(r, vector<bool>(c));
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
if (a[i][j] == 5) {
bool ok = true;
for (int x = max(0, i - 1); x <= min(r - 1, i + 1); x++)
for (int y = max(0, j - 1); y <= min(c - 1, j + 1); y++)
if ((x != i || y != j) && a[x][y] == 5)
ok = false;
if (ok)
for (int x = max(0, i - 1); x <= min(r - 1, i + 1); x++)
for (int y = max(0, j - 1); y <= min(c - 1, j + 1); y++)
if (a[x][y] == 1)
seen[x][y] = true;
}
int yes = 0, no = 0;
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
if (a[i][j] == 1) {
if (seen[i][j])
++yes;
else
++no;
}
cout << yes << ' ' << no << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。