宣告一個較大的陣列,並忽略邊緣元素,便不必檢查 array-bounds。
If you use a slightly bigger array and ignore the elements on the edge, then it becomes unnecessary to check the array bounds.
除此之外,因為使用 putchar
的緣故,便無法使用 sync_with_stdio(0)
。
Also, because of the usage of putchar
, sync_with_stdio(0)
can not be used.
UVa Link
#include <iostream>
int main() {
std::cin.tie(0);
for (int i = 1;; i++) {
int m, n, arr[102][102] = { 0 };
std::cin >> m >> n;
if (!m && !n) break;
std::cout << ((i == 1) ? "" : "\n") << "Field #" << i << ":\n";
std::cin.get(); // Ignore '\n'
for (int j = 1; j <= m; j++) {
for (int k = 1; k <= n; k++) {
char in;
std::cin.get(in);
if (in == '*') {
arr[j][k] = -100;
arr[j - 1][k - 1]++;
arr[j - 1][k]++;
arr[j - 1][k + 1]++;
arr[j][k - 1]++;
arr[j][k + 1]++;
arr[j + 1][k - 1]++;
arr[j + 1][k]++;
arr[j + 1][k + 1]++;
}
}
std::cin.get(); // Ignore '\n'
}
for (int j = 1; j <= m; j++) {
for (int k = 1; k <= n; k++) {
if (arr[j][k] < 0) putchar('*');
else putchar(arr[j][k] + '0');
}
putchar('\n');
}
}
}