• P1162 填涂颜色题解


    题目传送门

    理解与感悟

    1、从边缘出发进行思考。
    2、把外围所有0涂色干掉,再剩下的0就是被包裹住的0,这些0需要修改为2.
    3、所以OI的竞赛题,几乎没有祼的模板题,都是需要一点点思维难度的。这需要进行训练,刷题,没有别的办法。

    #include <bits/stdc++.h>
    
    using namespace std;
    const int N = 40;
    
    int n;
    int a[N][N];
    int b[N][N];
    int dx[] = {0, 0, -1, 1};
    int dy[] = {-1, 1, 0, 0};
    struct coord {
        int x, y;
    };
    
    //广度优先搜索
    void bfs(int x, int y) {
        queue<coord> q;
        q.push({x, y});
        while (!q.empty()) {
            coord p = q.front();
            q.pop();
            b[p.x][p.y] = -1;
    
            for (int i = 0; i < 4; i++) {
                int x1 = p.x + dx[i], y1 = p.y + dy[i];
                if (b[x1][y1] >= 0 && x1 >= 1 && x1 <= n && y1 >= 1 && y1 <= n && a[x1][y1] == 0) {
                    q.push({x1, y1});
                    b[x1][y1] = -1;
                }
            }
        }
    }
    
    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];
            }
    
        //思路:从边缘(四条外边),找0,然后BFS找出所有区域,这些区域就是不被圈起来的范围,进行标识,再取反
        for (int i = 1; i <= n; i++)
            if (a[1][i] == 0) bfs(1, i);    //第一行
    
        for (int i = 1; i <= n; i++)
            if (a[i][1] == 0) bfs(i, 1);    //第一列
    
        for (int i = 1; i <= n; i++)
            if (a[n][i] == 0) bfs(n, i);      //最后一行
    
        for (int i = 1; i <= n; i++)
            if (a[i][n] == 0) bfs(i, n);      //最后一列
    
        //输出
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (b[i][j] == -1) cout << 0 << " ";
                else if (b[i][j] == 0) cout << 2 << " ";
                else cout << b[i][j] << " ";
            }
            cout << endl;
        }
        return 0;
    }
    
  • 相关阅读:
    区块链
    git在IDEA中的使用
    hadoop linux 杂记
    idea java web 使用说明
    克隆虚拟机,解决网卡问题
    最小化CentOS6.7(64bit)---安装mysql5.5、jdk、tomcat
    爬虫学习笔记(1)--环境准备与正则表达式
    图论 BZOJ 3669 [Noi2014]魔法森林
    Manacher Ural 1297 Palindrome
    动态规划,贪心 APIO 2015 Sculptures
  • 原文地址:https://www.cnblogs.com/littlehb/p/15070102.html
Copyright © 2020-2023  润新知