洛谷 P1162 填涂颜色

题目

P1162 填涂颜色

分析

主要思路见信息学奥赛一本通 1359:围成面积

这里,我们把圈外的格子全部填3,输出时,3变0,原来0变2即可。

代码

#include<iostream>
#include<queue>
using namespace std;

int n;
int a[34][34];  // 矩阵
struct point { int x, y; };  // 表示点的结构体
queue<point> q;  // 队列
int dir[8][2] = { -1,0,0,1,1,0,0,-1 };  // 方向数组

// 检查
bool check(int x, int y) {
    return x >= 0 && x <= n + 1 && y >= 0 && y <= n + 1 && a[x][y] == 0;
}

// 入队
void que_add(int x, int y) {
    point pos;
    pos.x = x, pos.y = y;  // 设置坐标
    q.push(pos);
    a[x][y] = 3;  // 染色
}

// bfs涂色
void bfs(int x, int y) {
    que_add(x, y);
    while (q.size()) {
        point t = q.front();
        q.pop();

        // 扩展
        for (int i = 0; i < 4; i++) {
            int nx = t.x + dir[i][0], ny = t.y + dir[i][1];
            if (check(nx, ny)) que_add(nx, ny);
        }
    }

    // 调整
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++) {
            // 两个if不能调
            if (a[i][j] == 0) a[i][j] = 2;
            if (a[i][j] == 3) a[i][j] = 0;
        }
}

int main(){
    cin >> n;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++) cin >> a[i][j];
    bfs(0, 0);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) cout << a[i][j] << " ";
        cout << endl;
    }
    
    return 0;
}

评测结果 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值