Sci_8633 @ 2024-07-13 17:33:25
经检验,问题出在bfs()函数中。
#include<bits/stdc++.h>
using namespace std;
int n;
int dx[4]={0,0,-1,1};
int dy[4]={1,-1,0,0};
int vis[35][35];
char s[35][35];
struct node{
int x;
int y;
};
queue<node>q;
void bfs(int x,int y){
q.push({x,y});
while(!q.empty()){
node a=q.front();
q.pop();
for(int i=0;i<4;++i){
int nx=a.x+dx[i];
int ny=a.y=dy[i];
if(nx>=1&&nx<=n&&ny>=1&&ny<=n&&vis[nx][ny]==0&&s[nx][ny]=='0'){
vis[nx][ny]=1;
s[nx][ny]='2';
q.push({nx,ny});
}
}
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
cin>>s[i][j];
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
if(i==1&&s[i][j]=='0'||i==n&&s[i][j]=='0'||j==1&&s[i][j]=='0'||j==n&&s[i][j]=='0') /*靠边的‘0’未被包裹*/
vis[i][j]=-1;
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
if(vis[i][j]!=-1){
vis[i][j]=1;
bfs(i,j);
break;
}
for(int i=1;i<=n;++i,cout<<'\n')
for(int j=1;j<=n;++j)
if(vis[i][j]==-1){
s[i][j]='0';
cout<<s[i][j]<<' ';
}else cout<<s[i][j]<<' ';
return 0;
}
by Sci_8633 @ 2024-07-13 17:34:13
输出时1字框中的2都是0
by wby_1234 @ 2024-07-13 17:56:58
题号说一下,Please
by wuzhitong @ 2024-07-18 18:52:07
dfs的AC代码可以参考一下:
#include<bits/stdc++.h>
using namespace std;
int dx[4]={0,0,1,-1},dy[4]={1,-1,0,0},n,s;
int a[31][31];
void dfs(int x,int y)
{
if(x<1||y<1||x>n||y>n||a[x][y]!=0)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];
for(int i=1;i<=n;i++)dfs(1,i);
for(int i=1;i<=n;i++)dfs(i,n);
for(int i=1;i<=n;i++)dfs(i,1);
for(int i=1;i<=n;i++)dfs(n,i);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(a[i][j]==3)cout<<"0 ";
if(a[i][j]==1)cout<<"1 ";
if(a[i][j]==0)cout<<"2 ";
}
cout<<"\n";
}
return 0;
}
(求关 QWQ