题目
分析
主要思路见信息学奥赛一本通 1359:围成面积
这里,我们把圈外的格子全部填3,输出时,3变0,原来0变2即可。
代码
#include<iostream>
#include<queue>
using namespace std;
int n;
int a[34][34]; // 矩阵
struct point { int x, y; }; // 表示点的结构体
queue<point> q; // 队列
int dir[8][2] = { -1,0,0,1,1,0,0,-1 }; // 方向数组
// 检查
bool check(int x, int y) {
return x >= 0 && x <= n + 1 && y >= 0 && y <= n + 1 && a[x][y] == 0;
}
// 入队
void que_add(int x, int y) {
point pos;
pos.x = x, pos.y = y; // 设置坐标
q.push(pos);
a[x][y] = 3; // 染色
}
// bfs涂色
void bfs(int x, int y) {
que_add(x, y);
while (q.size()) {
point t = q.front();
q.pop();
// 扩展
for (int i = 0; i < 4; i++) {
int nx = t.x + dir[i][0], ny = t.y + dir[i][1];
if (check(nx, ny)) que_add(nx, ny);
}
}
// 调整
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
// 两个if不能调
if (a[i][j] == 0) a[i][j] = 2;
if (a[i][j] == 3) a[i][j] = 0;
}
}
int main(){
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) cin >> a[i][j];
bfs(0, 0);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) cout << a[i][j] << " ";
cout << endl;
}
return 0;
}