• nyoj92-图像有用区域【BFS】


    “ACKing”同学以前做一个图像处理的项目时,遇到了一个问题,他需要摘取出图片中某个黑色线圏成的区域以内的图片,现在请你来帮助他完成第一步,把黑色线圏外的区域全部变为黑色。

         

                    图1                                                        图2 

    已知黑线各处不会出现交叉(如图2),并且,除了黑线上的点外,图像中没有纯黑色(即像素为0的点)。

    输入描述:

    第一行输入测试数据的组数N(0<N<=6)
    每组测试数据的第一行是两个个整数W,H分表表示图片的宽度和高度(3<=W<=1440,3<=H<=960)
    随后的H行,每行有W个正整数,表示该点的像素值。(像素值都在0到255之间,0表示黑色,255表示白色)
    

    输出描述:

    以矩阵形式输出把黑色框之外的区域变黑之后的图像中各点的像素值。

    样例输入:

    复制

    1
    5 5
    100 253 214 146 120
    123 0 0 0 0
    54 0 33 47 0
    255 0 0 78 0
    14 11 0 0 0
    

    样例输出:

    0 0 0 0 0
    0 0 0 0 0
    0 0 33 47 0
    0 0 0 78 0
    0 0 0 0 0

    思路:这算是一道比较经典的BFS,简单说一下思路,就不打注释了,会BFS的一看就懂,不会的先掌握BFS再看就明白了。

    从起点开始搜,如果结点的值不等于0就赋值为0,然后继续向其邻接的节点搜,如果碰到0这个结点就不再搜,所以最后只剩下由一圈0围成的图形。考虑边界问题,所以在四周围一圈1,这样就可以从(0,0)开始一直搜下去了。

    #include <iostream>
    #include <cstdio>
    #include <vector>
    #include <cstring>
    #include <algorithm>
    #include <string>
    #include <queue>
    using namespace std;
    int m[965][1445];
    int w,h;   
    struct node  
    {
        int r,c;
    };
    queue <node> que;
    int d[4][2]={1,0,-1,0,0,-1,0,1};  
    void BFS()
    {
        node n;
        n.c=0,n.r=0;
        que.push(n);
        while(!que.empty())
        {
            int x,y;
            node front=que.front();
            que.pop();
            for(int i=0;i<4;++i)
            {
                x=front.c+d[i][0];
                y=front.r+d[i][1];
                if(x>=0 && x<=h+1 && y>=0 && y<=w+1 && m[x][y]>0)
                {
                    m[x][y]=0;
                    node n1;
                    n1.c=x,n1.r=y;
                    que.push(n1);
                }
            }
        }
    }
    int main()
    {
        int t;
        scanf("%d",&t);
        while(t--)
        {
            scanf("%d%d",&w,&h);
            for(int i=1;i<=h;++i)
            for(int j=1;j<=w;++j)
                scanf("%d",&m[i][j]);
        for(int i=0;i<=h+1;++i)
        {
            m[i][0]=1;
            m[i][w+1]=1;
        }
        for(int i=0;i<=w+1;++i)
        {
            m[0][i]=1;
            m[h+1][i]=1;
        }
        BFS();
        for(int i=1;i<=h;++i)
        {
            for(int j=1;j<w;++j)
            {
                printf("%d ",m[i][j]);
            }
             printf("%d
    ",m[i][w]);
        }
        }
        return 0;
    }
    
  • 相关阅读:
    css盒子模型之内边距padding及简写
    css盒子模型之宽度和高度
    windows 组策略
    windows 快捷键
    cmd 命令快捷键
    django 远程访问
    django 部署在 apache2 上面
    国内常用开源镜像站
    ubuntu1804自带官方源
    ubuntu1604 apt华为国内源
  • 原文地址:https://www.cnblogs.com/aerer/p/9931004.html
Copyright © 2020-2023  润新知