关键对矩阵周围一圈的0进行判断哪些0和他联通,进行标记
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int,int> pii;
const int N = 2e2 + 10;
int g[N][N];
int n;
pii q[N*N];
bool st[N][N];
bool vis[N][N];
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
void bfs(int sx, int sy){
int hh = 0, tt = 0;
q[0] = {sx,sy};
while(hh <= tt){
pii t = q[hh++];
for(int i = 0; i < 4; i++){
int a = t.x + dx[i], b = t.y + dy[i];
if(a >= 0 && a < n && b >= 0 && b < n && !st[a][b] && g[a][b] == 1){
st[a][b] = true;
q[++tt] = {a,b};
}
}
}
}
void bfs2(int sx, int sy){//记录与边界0联通的0
int hh = 0, tt = 0;
q[0] = {sx,sy};
int flag = 0;
while(hh <= tt){
pii t = q[hh++];
for(int i = 0; i < 4; i++){
int a = t.x + dx[i], b = t.y + dy[i];
if(a < 0 || a >= n || b < 0 || b >= n){
//如果不从矩形的边界进行判断,加上下面注释的代码要不2测试点错,要不4测试点错
// flag = 1;
// if(g[t.x][t.y] == 0){
// vis[t.x][t.y] = true;
// }
continue;
}
// if(flag){
if(!vis[a][b] && g[a][b] == 0){
vis[a][b] = true;
q[++tt] = {a,b};
}
// }
}
}
}
int main(){
cin >> n;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cin >> g[i][j];
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(!st[i][j] && g[i][j] == 1){
bfs(i,j);
}
}
}
// cout << "1sdrf" << endl;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if((i == 0 || i == n - 1 || j == 0 || j == n - 1) &&!vis[i][j] && g[i][j] == 0){
bfs2(i,j);
}
}
}
// cout << "2sdrf" << endl;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(!st[i][j] && !vis[i][j]){
cout << "2" <<" ";
}
else{
cout << g[i][j]<<" ";
}
}
puts("");
}
return 0;
}