这道题的标签是```BFS```不太适合用```DFS```做
可以参考一下[P1506 拯救oibh总部](https://www.luogu.com.cn/problem/P1506)
这题这样写:
```
#include<bits/stdc++.h>
using namespace std;
struct data{
int x,y;
};
queue<data>q;
int n,a[1001][1001];
bool vis[1001][1001];
void bfs(int x,int y){
vis[x][y]=1;
q.push({x,y});
while(!q.empty()){
int w=q.front().x,e=q.front().y;
q.pop();
if(a[w+1][e]==0 && w!=n && !vis[w+1][e]){
vis[w+1][e]=1;
q.push({w+1,e});
}
if(a[w-1][e]==0 && w!=1 && !vis[w-1][e]){
vis[w-1][e]=1;
q.push({w-1,e});
}
if(a[w][e-1]==0 && e!=1 && !vis[w][e-1]){
vis[w][e-1]=1;
q.push({w,e-1});
}
if(a[w][e+1]==0 && e!=n && !vis[w][e+1]){
vis[w][e+1]=1;
q.push({w,e+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]==1)vis[i][j]=1;
}
}
for(int i=1;i<=n;i+=n-1){
for(int j=1;j<=n;j++){
if(vis[i][j])continue;
bfs(i,j);
}
}
for(int i=1;i<=n;i+=n-1){
for(int j=1;j<=n;j++){
if(vis[j][i])continue;
bfs(j,i);
}
}
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<<'\n';
}
return 0;
}
```
by QAQ_YTH @ 2023-02-17 22:10:51
或者看看题解学学别的大神的做法,也可以做出来。洛谷的题都有一些详细的[题解](https://www.luogu.com.cn/problem/solution/P1162),相信像我这样的蒟蒻也都能看懂的
by QAQ_YTH @ 2023-02-17 22:33:22
@[LxSmill](/user/733980) 这是我这道题的深搜代码 希望可以帮到你
```cpp
#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;
}
```
by _Mikasa @ 2023-03-01 20:06:39