# 填涂颜色（dfs）

0

```#include<iostream>
using namespace std;

const int MAXN = 30 + 5;
int n;
int map[MAXN][MAXN];
bool vis[MAXN][MAXN];
int dx[] = { 0, 0, 0, -1, 1};
int dy[] = { 0, 1, -1, 0, 0};

void dfs(int x, int y)
{

if(x >= 0 && x <= n + 1 && y >= 0 && y <= n + 1)
{
if(map[x][y] == 1 || map[x][y] == 3)
return;
else
{
map[x][y] = 3;
for(int i = 1; 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 >> map[i][j];
dfs(0, 0);

for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(map[i][j] == 3)
map[i][j] = 0;
else if(map[i][j] == 0)
map[i][j] = 2;
}
}

for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
cout << map[i][j] << " ";
}

cout << endl;
}
return 0;
}```

```#include<iostream>
using namespace std;

const int MAXN = 30 + 5;
int n;
int map[MAXN][MAXN];
bool vis[MAXN][MAXN];
int dx[] = { 0, 0, 0, -1, 1};
int dy[] = { 0, 1, -1, 0, 0};

void dfs(int x, int y)
{

if(x >= 1 && x <= n && y >= 1 && y <= n)
{
if(map[x][y] == 1 || map[x][y] == 3)
return;
else
{
map[x][y] = 3;
for(int i = 1; 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 >> map[i][j];
dfs(1, 1);

for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(map[i][j] == 3)
map[i][j] = 0;
else if(map[i][j] == 0)
map[i][j] = 2;
}
}

for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
cout << map[i][j] << " ";
}

cout << endl;
}
return 0;
}```

goalltheway | 初学一级 | 园豆：133

Drophair 2个月前

@Drophair: 嗯，您能帮我解答一下吗？

goalltheway 1个月前

0

Drophair | 园豆：220 (菜鸟二级) | 2020-09-29 21:29
0

# include <bits/stdc++.h>

using namespace std;
int a[32][32],b[32][32];
int dx[5]={0,-1,1,0,0};
int dy[5]={0,0,0,-1,1};
int n,i,j;
void dfs(int p,int q){
int i;
if (p<0||p>n+1||q<0||q>n+1||a[p][q]!=0) return;
a[p][q]=1;
for (i=1;i<=4;i++) dfs(p+dx[i],q+dy[i]);
}
int main(){
cin>>n;
for (i=1;i<=n;i++)
for (j=1;j<=n;j++){
cin>>b[i][j];
if (b[i][j]0) a[i][j]=0;
else a[i][j]=2;
}
dfs(0,0);
for (i=1;i<=n;i++){
for (j=1;j<=n;j++)
if (a[i][j]
0) cout<<2<<' ';
else cout<<b[i][j]<<' ';
cout<<'\n';
}
}

您需要登录以后才能回答，未注册用户请先注册