luogu-P1162 填涂颜色【DFS】【看题解啊】【二刷呀】

#include
using namespace std;
#define what(x) cout << #x << " is " << x << endl;
#define LL long long
vector<vector<int>> dir = {{0,-1}, {0,1}, {-1,0}, {1,0}};
int n;
int x = 0, y = 0;
void dfs(vector<vector<int>> &g)
{
    g[x][y] = 3;
    for (int i = 0; i < 4; ++i) {
        x += dir[i][0];
        y += dir[i][1];
        if (x >= 0 && x < n+2 && y >= 0 && y < n+2 && !g[x][y])
            dfs(g);
        x -= dir[i][0];
        y -= dir[i][1];
    }
}

int main()
{
    cin >> n;
    vector<vector<int>> g(n+2, vector<int>(n+2, 0));
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            cin >> g[i][j];
        }
    }
    dfs(g);
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (g[i][j] == 3) cout << 0;
            else if (g[i][j] == 0) cout << 2;
            else cout << 1;
            cout << ' ';
        }
        cout << endl;
    }
    return 0;
}

你可能感兴趣的:(洛谷)