传送门https://www.luogu.com.cn/problem/P1162
题目大意是给一个n*n的矩阵,矩阵中有1和0两种数字,现在要求将被1框起来的0全部变成2并输出(注意0不能贴边界)
思路考虑:设一个状态数组,找连通块,将边界为0,且连通的所有0全部赋值为true,且将所有1全部赋值为true,这些是不需要修改的,直接输出原数字,然后对于其他的数字直接输出2即可(false)
兄弟题https://www.luogu.com.cn/problem/P1506
贴代码
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
const int N=35;
int n;
int a[N][N];
bool check[N][N];
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
void bfs(int c,int d){
queue<pair<int,int>> q;
q.push({c,d});
while(q.size()){
auto t=q.front();
q.pop();
for(int i=0;i<4;++i){
int x=t.first+dx[i],y=t.second+dy[i];
if(x<=n&&y<=n&&y>=1&&x>=1&&!check[x][y]) check[x][y]=1,q.push({x,y});
//注意判断条件,如果这个点是0且满足条件就入队
}
}
}
int main(){
cin>>n;
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
cin>>a[i][j];
if(a[i][j]==1) check[i][j]=1;
}
}
for(int i=1;i<=n;i+=(n-1)){
for(int j=1;j<=n;++j){
if(!check[i][j]) bfs(i,j); //第1行和第n行
if(!check[j][i]) bfs(j,i); //第1列和第n列
}
}
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
if(check[i][j]) cout<<a[i][j]<<' ';
else cout<<2<<' ';
}
cout<<endl;
}
return 0;
}