公式
B - Count Adjacent Cells 解説 by en_translator
Solution 1
Cell \((i, j)\) has four edge-adjacent cells:
- cell \((i-1,\ j)\)
- cell \((i+1,\ j)\)
- cell \((i,\ j-1)\)
- cell \((i,\ j+1)\)
Inspect each of them to check if it exists.
Solution 2
If the size of the grid is \(1 \times 1\), the answer for cell \((1,1)\) is \(0\).
If the size of the grid is \(1 \times W\) (\(W > 1\)), the answers for cells \((1,1), (1,W)\) are \(1\), and the others are \(2\).
If the size of the grid is \(H \times 1\) (\(H > 1\)), the answers for cells \((1,1), (H,1)\) are \(1\), and the others are \(2\).
If the size of the grid is \(H \times W\) (\(H,W > 1\)), the answer is:
- \(2\) for cells \((1,1), (1,W), (H,1), (H,W)\);
- otherwise, \(3\) for the cells in at least one of row \(1\), row \(H\), column \(1\), or column \(W\);
- otherwise, \(4\).
Handle these cases correctly, and your solution will be accepted.
Sample code (C++, Solution 1)
#include <iostream>
using std::cin;
using std::cout;
int main (void) {
int h, w;
cin >> h >> w;
int ans[h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
ans[i][j] = 0;
if (i-1 >= 0) ans[i][j]++;
if (i+1 < h) ans[i][j]++;
if (j-1 >= 0) ans[i][j]++;
if (j+1 < w) ans[i][j]++;
}
}
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (j > 0) { cout << " "; }
cout << ans[i][j];
}
cout << "\n";
}
return 0;
}
投稿日時:
最終更新: