输入:
6
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1
输出:
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1
代码如下:
#include <iostream>
using namespace std;
const int N = 40;
int mp[N][N], mps[N][N];
int n;
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
void dfs(int x, int y) {
for (int i = 0; i < 4; i++) {
int xx = x + dx[i], yy = y + dy[i];
if (xx < 0 || xx > n + 1 || yy < 0 || yy > n + 1 || mps[xx][yy])
continue;
mps[xx][yy] = 1;
dfs(xx, yy);
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
cin >> mp[i][j];
mps[i][j] = mp[i][j];
}
dfs(0, 0);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (mps[i][j])
cout << mp[i][j] << " ";
else
cout << 2 << " ";
}
cout << endl;
}
return 0;
}