shipeiqian @ 2022-08-09 10:41:04
#include <bits/stdc++.h>
using namespace std;
int n,a[35][35],b[35][35];
int dx[4]={0,0,-1,1};
int dy[4]={-1,1,0,0};
bool check(int x,int y){
if(x<1||y<1||x>n||y>n)return false;
if(a[x][y])return false;
return true;
}
void dfs(int x,int y){
if(check(x,y)){
a[x][y]=1;
for(int i=0;i<4;i++) {
int nx=x+dx[i];
int ny=y+dy[i];
dfs(nx,ny);
}
}
}
int main(){
cin >>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin >>b[i][j];
if(!b[i][j])a[i][j]=0;
else a[i][j]=2;
}
}
dfs(1,1);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(!a[i][j])cout <<2 <<" ";
else cout <<b[i][j] <<" ";
}
cout <<"\n";
}
return 0;
}
不会写BFS怎么办
by MONED @ 2022-08-09 11:07:02
从0 0开始dfs
by MONED @ 2022-08-09 11:10:36
我给的样例不用在意
by MONED @ 2022-08-09 11:14:38
你要是在不会 代码奉上
#include <bits/stdc++.h>
using namespace std;
const int K=35;
int n,dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
bool b1[K][K],b2[K][K];
void dfs(int x,int y)
{
if(x<0 || y<0 || x>n+1 || y>n+1 || !b2[x][y]) return;
b2[x][y]=0;
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>>b1[i][j];
for(int i=0;i<=n+1;++i) for(int j=0;j<=n+1;++j) b2[i][j]=!b1[i][j];
dfs(0,0);
for(int i=1;i<=n;++i)
{
for(int j=1;j<=n;++j)
{
if(b2[i][j]) cout<<2<<" ";
else cout<<b1[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
by shipeiqian @ 2022-08-09 11:23:45
@MONED 懂了,谢谢