哦对了 还有不知所以的宏
by Specter_LiZN @ 2024-08-31 16:19:36
@[Specter_LiZN](/user/465029) 我写了两份代码,你可以参考一下
bfs:
```
#include <bits/stdc++.h>
using namespace std;
int mp[31][31];
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
int n;
queue<int> q;
void bfs(int x,int y){
int x1,x2,y1,y2;
q.push(x);
q.push(y);
mp[x][y]=2;
while(!q.empty()){
x1=q.front();
q.pop();
y1=q.front();
q.pop();
for(int i=0;i<4;i++){
x2=x1+dx[i];
y2=y1+dy[i];
if(x2>=0&&x2<=n+1&&y2>=0&&y2<=n+1&&mp[x2][y2]==0){
q.push(x2);
q.push(y2);
mp[x2][y2]=2;
}
}
}
return;
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>mp[i][j];
}
}
bfs(0,0);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cout<<(mp[i][j]==0?2:(mp[i][j]==1?1:0))<<' ';
}
cout<<endl;
}
return 0;
}
```
dfs:
```
#include <bits/stdc++.h>
using namespace std;
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
int a[1001][1001],n;
bool vis[1001][1001];
void dfs(int x,int y){
if(x<0||x>n+1||y<0||y>n+1||vis[x][y]!=0) return ;
vis[x][y]=1;
for(int i=0;i<4;i++) dfs(x+dx[i],y+dy[i]);
}
signed 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]==0) vis[i][j]=0;
else vis[i][j]=2;
}
}
dfs(0,0);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(vis[i][j]==0) cout<<2<<" ";
else cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
```
by CQ天神 @ 2024-08-31 16:21:12
@[Specter_LiZN](/user/465029)
仅作参考,但这道题应该只能用bfs过吧
by Yxy7952 @ 2024-08-31 16:22:48
@[CQ天神](/user/959024)
感谢dalao!我再看看
by Specter_LiZN @ 2024-08-31 16:35:19
@[yixingyou](/user/936717)
的确是
但这个思路实际上哪种优先搜索都不算(好像
我想的是找到第一个可以被涂色的‘0’
by Specter_LiZN @ 2024-08-31 16:37:17
因为方阵内只有一个闭合圈,所以只需先遍历找到一个在闭合圈内的0,再深搜,把闭合圈里所有0变成2即可。
```cpp
#include<bits/stdc++.h>
using namespace std;
int n;
int a[31][31];
bool dfs[31][31];
bool dfs1(int x,int y){
dfs[x][y]=1;
if(x==0||x==n-1||y==0||y==n-1){
return 1;
}
if(dfs[x-1][y]==0&&a[x-1][y]==0&&dfs1(x-1,y)==1||dfs[x+1][y]==0&&a[x+1][y]==0&&dfs1(x+1,y)==1||dfs[x][y-1]==0&&a[x][y-1]==0&&dfs1(x,y-1)==1||dfs[x][y+1]==0&&a[x][y+1]==0&&dfs1(x,y+1)==1){
return 1;
}
return 0;
}
void dfs2(int x,int y){
if(a[x-1][y]==0){
a[x-1][y]=2;
dfs2(x-1,y);
}
if(a[x+1][y]==0){
a[x+1][y]=2;
dfs2(x+1,y);
}
if(a[x][y-1]==0){
a[x][y-1]=2;
dfs2(x,y-1);
}
if(a[x][y+1]==0){
a[x][y+1]=2;
dfs2(x,y+1);
}
return ;
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>a[i][j];
}
}
for(int i=1;i<n-1;i++){
for(int j=1;j<n-1;j++){
if(a[i][j]==0&&dfs1(i,j)==0){
dfs2(i,j);
a[i][j]=2;
for(int ii=0;ii<n;ii++){
for(int jj=0;jj<n;jj++){
cout<<a[ii][jj]<<' ';
}
cout<<endl;
}
return 0;
}
}
}
return 0;
}
```
by LiDingguang @ 2024-08-31 22:33:41