top1编程
← 返回题目
题解

填涂颜色

1 条题解

  • 0
    @ 2026-10-21 0:48:00

    1. 解题思路

    在方阵外补一圈0,从外圈起点搜索所有与外界连通的0。原矩阵中尚未被搜索到的0就是圈内空间,改为2。

    2. 坑点和注意事项

    n≤30。只走上下左右,不走对角;原有1必须保持,不能直接把所有0填2。

    3. 复杂度

    • 时间复杂度:O(n²)。
    • 空间复杂度:O(n²)。
    /*
    思路:在方阵外补一圈0,从外圈起点搜索所有与外界连通的0。原矩阵中尚未被搜索到的0就是圈内空间,改为2。
    关键规则与坑点:n≤30。只走上下左右,不走对角;原有1必须保持,不能直接把所有0填2。
    时间复杂度:O(n²)。空间复杂度:O(n²)。
    */
    #include <bits/stdc++.h>
    using namespace std;
    int a[32][32];
    bool out[32][32];
    int main()
    {
        int n;
        cin >> n;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
                cin >> a[i][j];
        queue<pair<int, int>> q;
        q.push({0, 0});
        out[0][0] = true;
        int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
        while (!q.empty())
        {
            int i = q.front().first, j = q.front().second;
            q.pop();
            for (int k = 0; k < 4; k++)
            {
                int x = i + dx[k], y = j + dy[k];
                if (x >= 0 && x < n + 2 && y >= 0 && y < n + 2 && !a[x][y] && !out[x][y])
                {
                    out[x][y] = true;
                    q.push({x, y});
                }
            }
        }
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
                cout << (a[i][j] ? 1 : out[i][j] ? 0 : 2) << (j == n ? '\n' : ' ');
    }
    
    • 1