nyoj--92 图像有用区域(bfs)

23 篇文章 0 订阅
6 篇文章 0 订阅

nyoj 92

题解

此题实际上是要遍历”0”圈以外的数,把它们置为0。
BFS遍历是一层一层的,对于每个当前正遍历的结点,如果它的邻接点(邻近的元素)为0,那就不作为扩展结点放入队列中,否则将其置为0并作为扩展节点放入队列。
这种方法需要把整个图像(矩阵)套在一个不是”0”的圈里,像装裱一副字画?

#include <iostream>
#include <cstdio>
#include <queue>
#include <fstream>
#include <algorithm>
using namespace std;

typedef pair<int, int> pii;
const int maxw = 1445;
const int maxh = 965;
int   g[maxh][maxw];
int   w, h, t;
int   dir[4][2] = { {0, 1}, {-1, 0}, {1, 0}, {0, -1} };

void bfs()
{
    queue<pii> Q;
    Q.push(make_pair(0, 0));
    while(!Q.empty())
    {
        pii p = Q.front();
        Q.pop();
        int x = p.first, y = p.second;
        for(int i = 0; i < 4; ++i)
        {
            int newx = x + dir[i][0], newy = y + dir[i][1];
            if(newx < 0 || newx > h + 1 || newy < 0 || newy > w + 1 || g[newx][newy] == 0) continue;
            g[newx][newy] = 0;
            Q.push(make_pair(newx, newy));
        }
    }
}

int main()
{
    #ifdef LOCAL
    fstream cin("data.in");
    #endif // LOCAL

    ios::sync_with_stdio(false);
    cin.tie(0);
    for(cin >> t; t--; )
    {
        cin >> w >> h;
        for(int i = 0; i < maxh; ++i) fill(*(g + i), *(g + i) + maxw, 1);

        for(int i = 1; i <= h; ++i)
        {
            for(int j = 1; j <= w; ++j)
            {
                cin >> g[i][j];
            }
        }
        bfs();
        for(int i = 1; i <= h; ++i)
        {
            for(int j = 1; j <= w; ++j)
            {
                cout << g[i][j] << " ";
            }
            cout << endl;
        }
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值