逆向思维,把闭合圈外的0全部消灭,剩下闭合圈里的0
实现方法:在原有的矩阵基础上四周再加一层,保证所有闭合圈外的的0都能扫描到
我的代码:
#include<bits/stdc++.h>
using namespace std;
int n;
int a[50][50], dx[4]={0, -1, 0, 1}, dy[4]={-1, 0, 1, 0};
void dfs(int x, int y){
if(x<0 || x>n+1 || y<0 || y>n+1 || a[x][y])
return;
a[x][y] = 3;
for(int i=0; i<4; i++)
dfs(x+dx[i], y+dy[i]);
}
int main(){
cin>>n;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
cin>>a[i][j];
}
}
dfs(0, 0);
for(int i=1; i<=n; i++){
for(int j=1; j<=n ;j++){
if(a[i][j]==3){
cout<<"0 ";
}else if(a[i][j]==1){
cout<<"1 ";
}else{
cout<<"2 ";
}
}
cout<<endl;
}
}