ZackofZHOU @ 2023-07-08 17:04:23
下列是蒟蒻的代码:
#include<iostream>
using namespace std;
int map[35][35],n;
bool vis[35][35];
int dx[] = {-1,1,0,0},dy[] = {0,0,1,-1};
void dfs(int x,int y)//深度优先搜索
{
if(map[x][y] == 1 || vis[x][y] || x > n || y > n || x < 1 || y < 1)
return ;
vis[x][y] = true;
for(int i = 0;i < 4;i++)
dfs(dx[i] + x,dy[i] + y);
}
int main()
{
cin >> n;
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++)
cin >> map[i][j];
for(int i = 1;i <= n;i++)
dfs(1,i);
for(int i = 1;i <= n;i++)
dfs(i,1);
dfs(n,n);
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
if(!vis[i][j])
if(map[i][j] == 1)
cout << 1 << ' ';
else
cout << 2 << ' ';
else
cout << 0 << ' ';
cout << '\n';
}
return 0;
}
by ZackofZHOU @ 2023-07-08 17:18:43
已找出解
#include<iostream>
using namespace std;
int map[35][35],n;
bool vis[35][35];
int dx[] = {-1,1,0,0},dy[] = {0,0,1,-1};
void dfs(int x,int y)//深度优先搜索
{
if(map[x][y] == 1 || vis[x][y] || x > n || y > n || x < 1 || y < 1)
return ;
vis[x][y] = true;
for(int i = 0;i < 4;i++)
dfs(dx[i] + x,dy[i] + y);
}
int main()
{
cin >> n;
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++)
cin >> map[i][j];
for(int i = 1;i <= n;i++)
{
dfs(1,i);
dfs(i,1);
dfs(i,n);
dfs(n,i);
}
dfs(n,n);
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
if(!vis[i][j])
if(map[i][j] == 1)
cout << 1 << ' ';
else
cout << 2 << ' ';
else
cout << 0 << ' ';
cout << '\n';
}
return 0;
}