acmwriter @ 2022-12-25 23:13:20
#include<bits/stdc++.h>
using namespace std;
int a[100][100],b[100][100];
int n;
int kx[4]={0,0,1,-1};
int ky[4]={1,-1,0,0};
void dfs(int x,int y)
{
int b,c;
a[x][y]=0;
for(int i=1;i<=4;i++)
{
b=x+kx[i];
c=y+ky[i];
if(b>=1&&b<=n&&c>=1&&c<=n&&a[b][c]==1)
dfs(b,c);
}
}
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]==0)a[i][j]=1;
else a[i][j]=2;
}
}
dfs(0,0);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(a[i][j]==0)cout<<2<<' ';
else cout<<b[i][j]<<' ';
}
cout<<'\n';
}
}
by whhsteven @ 2022-12-26 01:54:03
你的 dfs 为什么从
by _Mikasa @ 2023-03-01 20:09:09
@whhsteven 你看看我这个dfs内函数的写法
#include <bits/stdc++.h>
using namespace std;
int a[35][35],vist[35][35];
long long n;
void dfs(int i,int j){
if(i<0||j<0||i>n+1||j>n+1||vist[i][j]!=0){
return;
}
vist[i][j]=1;
dfs(i-1,j);
dfs(i+1,j);
dfs(i,j+1);
dfs(i,j-1);
}
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]==0){
vist[i][j]=0;
}else{
vist[i][j]=2;
}
}
}
dfs(0,0);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(vist[i][j]==0){
cout<<"2"<<" ";
}else{
cout<<a[i][j]<<" ";
}
}
cout<<endl;
}
return 0;
}