P1162 填涂颜色
题目链接https://www.luogu.com.cn/problem/P1162
题目分析
本题考查联通块,采用dfs,但直接查找被一围住的零有些困难,所以先查找外围的0,将它们都替换为3,最后将所有3变为0,0变为2。但是考虑到如下情况:
在map二维数组的外围再加入一圈0,将它们联通。
代码
#include<iostream>
using namespace std;
int dir[4][2] = {{ 1,0 }, { -1,0 }, { 0,1 }, { 0,-1 }};
int map[1001][1001];
int book[1001][1001];
int n;
void dfs(int x, int y)
{
map[x][y] = 3;
for (int k = 0; k < 4; k++)
{
int nx = x + dir[k][0];
int ny = y + dir[k][1];
if (nx >= 0 && ny >= 0 && nx <= n+1 && ny <= n+1&&!book[nx][ny]&&map[nx][ny]==0)
{
book[nx][ny] = 1;
dfs(nx, ny);
}
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> map[i][j];
book[0][0]=1;
dfs(0, 0);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (map[i][j] == 0)
map[i][j] = 2;
if (map[i][j] == 3)
map[i][j] = 0;
cout << map[i][j]<<" ";
}
cout << endl;
}
return 0;
}