【BFS】面积(C++)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/liuzich/article/details/99644542

Description
一幅图由0和*组成,编程计算由“*”号所围成的图形的面积。面积的计算方法是统计*号所围成的闭合曲线中0的数目。

Input
由0和*组成的字符矩阵,行列数均不超过50。对于此种输入方式,输入完成后按ctrl+z结束。

Output
面积数

Sample Input

input 1
000000000
0000**000
000*00*00
00*000*00
000***000
000000000
input 2
********000000000000000**********
*000000*000000000000000*00000000*
*000000*****************00000000*
0000000000000000000000000000000
*********************************

Sample Output

output 1
5
output 2
59

HINT

思路:我看了这题后,以为只要直接将以第一个点当初始位消掉外面的0,再搜索0就行了,但实际没那么简单,你看看下面一个例子:
(例子中1代表*)
011111110
111111111
011111110
111101111
011111110
011111110
111111111
这样的话,输出为8,但实际是1,所以该怎么办呢?
其实很简单,只要在外面加一圈0再消除就可以了,下面是例子加了一圈0后的样子:
(例子中1代表*)
00000000000
00111111100
01111111110
00111111100
01111011110
00111111100
00111111100
01111111110
00000000000
这样边缘的0就会在消除边框的同时消掉了。
但还有一点,就是判断那个点是否为0的时候,还要判断是否越界
下面是代码:

#include<bits/stdc++.h>
using namespace std;
string s;
bool ok[51][51];
int n=0,m;
int p[501],q[501],xx[5]={0,0,0,1,-1},yy[5]={0,1,-1,0,0};
int main() {
    memset(ok,true,sizeof(ok));
    while(cin>>s)
    {
        n++;
        int len=s.length();
        m=len;
        for(int i=0;i<len;i++)
        {
            if(s[i]=='*')
            {
                ok[n][i+1]=false;
            }
             
            else
            {
                ok[n][i+1]=true;
            }
        }
    }
    int head=1;
    int tail=1;
    while(head<=tail)
    {
        for(int i=1;i<=4;i++)
        {
            int h=p[head]+xx[i];
            int l=q[head]+yy[i];
            if(ok[h][l]==true&&h>=0&&l>=0&&h<=n+1&&l<=m+1)
            {
                tail++;
                p[tail]=h;
                q[tail]=l;
                ok[h][l]=false;
            }
        }
        head++;
    }
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(ok[i][j])
            {
                ans++;
            }
        }
    }
    cout<<ans<<endl;
 
    return 0;
}

猜你喜欢

转载自blog.csdn.net/liuzich/article/details/99644542
今日推荐