题解:P1162 填涂颜色

· · 题解

solution

搜索入门。

直接找圈里的 0 有点困难,考虑找出圈外的 0 并打上标记,最后输出时对于没打标记的 0 输出 2,其他的输出原数组即可。这个标记的过程就用搜索解决,这里用了深搜,具体的:

code

#include<bits/stdc++.h>
using namespace std;
int a[40][40], b[40][40], n;
void dfs(int x, int y){
    if(x<0||x>n+1||y<0||y>n+1||a[x][y])
        return;
    a[x][y]=1;
    dfs(x, y-1);
    dfs(x, y+1);
    dfs(x-1, y);
    dfs(x+1, y);
}
int main(){
    cin >> n;
    for(int i=1; i<=n; i++)
        for(int j=1; j<=n; j++)
            cin >> a[i][j],
            b[i][j]=a[i][j];
    dfs(0, 0);
    for(int i=1; i<=n; i++){
        for(int j=1; j<=n; j++)
            cout << (a[i][j]?b[i][j]:2) << ' ';
        cout << '\n';
    }
    return 0;
}