洛谷 P1162 填涂颜色 DFS

P1162 填涂颜色

https://www.luogu.com.cn/problem/P1162

qaq搜索好抽象啊,蒟蒻表示难以理解,搞半天才做出来一道题,很挫败www

思路

染色法。找墙壁外的连通块0,染成新颜色。
注意边界问题:为了照顾到边缘的连通块,我们的范围要设置为0 ~ n + 1

代码

#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;
const int N = 35;
int n;
int a[N][N], b[N][N];
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
bool vis[N][N];

void dfs (int x, int y) {
    
    for (int i = 0; i < 4; i ++) {
        int xx = x + dx[i], yy = y + dy[i];
        if (xx > n + 1 || xx < 0 || yy > n + 1 || yy < 0 || a[xx][yy]) //这个边界很玄幻啊
            continue;
        a[xx][yy] = 3;
        dfs (xx, yy);
    }

}

int main(){
    cin >> n;
    for (int i = 1; i <= n; i ++)
        for (int j = 1; j <= n; j ++) 
            cin >> a[i][j];

    dfs (1, 1);
            
    for (int i = 1; i <= n; i ++){
        for (int j = 1; j <= n; j ++) {
            if (a[i][j] == 0)
                cout << 2 << ' ';
            else if (a[i][j] == 3)
                cout << 0 << ' ';
            else
                cout << 1 << ' ';
        }
    cout << endl;
    }    
}
//找墙外联通块
posted @ 2022-03-31 19:07  Sakana~  阅读(27)  评论(0编辑  收藏  举报