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\n",m[i][w]);
    }
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章