求助 改进过后从四个角一起开始遍历也只过3个点

P1162 填涂颜色

huashuo @ 2024-04-02 23:24:26

#include<bits/stdc++.h>
using namespace std;
int Map[32][32];
queue<int> nowx;
queue<int> nowy;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int vis[32][32];
int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++)
        {
            scanf("%d", &Map[i][j]);
        }
    }

    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++)
        {
            if(Map[i][j] == 0)
            Map[i][j] = 2;
        }
    }
    for(int i = 1; i <= n; i++) if(Map[1][i] == 2)Map[1][i] = 0;
    for(int i = 1; i <= n; i++) if(Map[i][1] == 2)Map[i][1] = 0;
    for(int i = 1; i <= n; i++) if(Map[i][n] == 2)Map[i][n] = 0;
    for(int i = 1; i <= n; i++) if(Map[n][i] == 2)Map[n][i] = 0;
    vis[1][1] = 1;
    nowx.push(1);
    nowy.push(1);
    nowx.push(n);
    nowy.push(n);
    nowx.push(1);
    nowy.push(n);
    nowx.push(n);
    nowy.push(1);
    while(!nowx.empty())
    {
        for(int i = 0; i < 4; i++)
        {
            int nextx = nowx.front() + dx[i];
            int nexty = nowy.front() + dy[i];
            if(Map[nextx][nexty]!=1 && vis[nextx][nexty] == 0 
                && nextx >=0 && nextx <= n
                && nexty >=0 && nexty <= n)
            {
                vis[nextx][nexty] = 1;
                Map[nextx][nexty] = 0;
                nowx.push(nextx);
                nowy.push(nexty);
            }
        }
        nowx.pop();
        nowy.pop();
    }

    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++)
        printf("%d ",Map[i][j]);
    printf("\n");
    }
    return 0;
    /*
    6
1 1 1 0 1 0
0 0 1 1 1 0
1 0 0 0 0 1
1 1 0 1 1 1
0 1 0 1 0 0
0 1 1 1 0 0
    */

}

by XiongYingHao @ 2024-04-25 22:28:05

可以多加一圈0,使n n的矩阵变为(n + 2) (n + 2 )的矩阵,亲测可行

加之前

加之后


|