#include <iostream>
#include <queue>
using namespace std;
int map[40][40] = {0};//0代表未染色,1代表染色了,3代表邊界外染色
int n;
struct node {
int x;
int y;
}n1;
queue<node> q;
void bfs(int x,int y) {
n1.x = x;
n1.y = y;
q.push(n1);
map[x][y] = 3;//開始第一個位置染上顏色
//
while (!q.empty()) {
int temp_x, temp_y;
temp_x = q.front().x;
temp_y = q.front().y;
q.pop();
if (temp_x - 1 > 0&& map[temp_x - 1][temp_y] == 0) {
n1.x = temp_x - 1;
n1.y = temp_y;
map[temp_x - 1][temp_y] = 3;
q.push(n1);
}
if (temp_x + 1 < n+2 && map[temp_x + 1][temp_y] == 0) {
n1.x = temp_x + 1;
n1.y = temp_y;
map[temp_x + 1][temp_y] = 3;
q.push(n1);
}
if (temp_y - 1 > 0 && map[temp_x][temp_y - 1] == 0) {
n1.x = temp_x;
n1.y = temp_y - 1;
map[temp_x][temp_y - 1] = 3;
q.push(n1);
}
if (temp_y + 1 < n + 2 && map[temp_x][temp_y + 1] == 0) {
n1.x = temp_x;
n1.y = temp_y + 1;
map[temp_x][temp_y + 1] = 3;
q.push(n1);
}
}
}
int main() {
cin >> n;
int temp;
for (int i = 1; i < n+1; i++)
{
for (int j = 1; j < n+1; j++)
{
cin >> temp;
map[i][j] = temp;
}
}
bfs(0, 0);
for (int i = 1; i < n + 1; i++)
{
for (int j = 1; j < n + 1; j++)
{
if (map[i][j] == 3) {
map[i][j] = 0;
}
else if (map[i][j]==0) {
map[i][j] = 2;
}
cout << map[i][j] << " ";
}
cout << endl;
}
return 0;
}
精妙之處,我在原圖的外層加了一圈0,使得我的bfs能夠直接最終將邊界外的0全部染上。