#include <iostream>
using namespace std;
int n, m;
int fix[8] = {-1, 1, 0, 0, -1, 1, -1, 1};//八个方向,上下左右,左上,左下,右上,右下
int fiy[8] = {0, 0, -1, 1, -1, 1, 1, -1};
const int N = 110;
int dl[N][N];
int ans[N][N];
void dfs(int x, int y) {
ans[x][y] = 0;//初始化
for (int i = 0; i < 8; i++) {
int xx = x + fix[i];
int yy = y + fiy[i];
if (dl[xx][yy] == 1)//周围有地雷
ans[x][y]++;
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> dl[i][j];
if (dl[i][j] == 1)
ans[i][j] = 9;
// if (dl[i][j]==0)
//dfs(i, j);不能放这里
//这是因为 dfs 函数内部的计算依赖于周围位置的状态,
//而这些状态可能在当前位置被处理之前尚未被初始化。
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (dl[i][j]==0)
dfs(i, j)
cout << ans[i][j] << " ";
}
cout << endl;
}
return 0;
}
想特别说一下容易错的点,一开始周围的没存入,不能用dfs,因为那个位置还未被初始化,这点需要尤其注意一下