原题链接:https://www.luogu.com.cn/problem/P1162
题意解读:要把闭合圈内的0填为2,DFS处理即可。
解题思路:
由于方阵内只有一个闭合圈,所以闭合圈以外的0一定和边缘相连通,只需要从边缘开始,把0的连通块全部标记为2
最后再输出时,2输出0,1输出1,0输出2,即可得解。
100分代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 35;
int g[N][N];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
int n;
void dfs(int x, int y)
{
g[x][y] = 2; //把和边缘连通的0染成2
for(int i = 0; i < 4; i++)
{
int nx = x + dx[i], ny = y + dy[i];
if(nx >= 1 && nx <= n && ny >= 1 && ny <= n && g[nx][ny] == 0)
{
dfs(nx, ny);
}
}
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
cin >> g[i][j];
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if((i == 1 || i== n || j == 1 || j == n) && g[i][j] == 0)
dfs(i, j);
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(g[i][j] == 0) cout << 2;
else if(g[i][j] == 2) cout << 0;
else cout << 1;
cout << " ";
}
cout << endl;
}
return 0;
}
标签:填涂,输出,int,洛谷题,闭合,nx,P1162 From: https://www.cnblogs.com/jcwy/p/18059558