AcWing1233.全球变暖

原题链接

解题思路:BFS(也可以使用DFS)

通过遍历一片连通块,如果该连通块中块的总数等于连通块中会被沉没的块的总数,则该连通块会被沉没。

#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
const int N = 1010;
int n;
char g[N][N];//记录图
bool st[N][N];//记录状态
typedef pair<int,int> PII;
int dx[4] = {-1,0,1,0},dy[4] = {0,-1,0,1};

void bfs(int x,int y,int &cnt,int &bnd)//之后要使用到cnt和bnd
{
    queue<PII> q;
    q.push({x,y});
    st[x][y] = true;//标记该点为走过的点
    
    while(q.size())
    {
        auto t = q.front();
        cnt ++;
        q.pop();
        bool is_bnd = false;初始化该点为四面不靠海的点,即不会被淹没
        for(int i = 0;i < 4;i ++)
        {
            int a = t.first + dx[i],b = t.second + dy[i];
            if(a < 0 && a >= n && b < 0 && b >= n) continue;
            if(st[a][b]) continue;
            if(g[a][b] == '.')
            {
                is_bnd = true;//将该点标记为会被淹没的点,即四面有任意一面靠海
                continue;
            }
            st[a][b] = true;
            q.push({a,b});
        }
        if(is_bnd) bnd ++;
    }
}
int main()
{
    cin >> n;
    for(int i = 0;i < n;i ++)
    {
        for(int j = 0;j < n;j ++)
        {
            cin >> g[i][j];
        }
    }
    int res = 0;
    for(int i = 0;i < n;i ++)
    {
        for(int j = 0;j < n;j ++)
        {
            if(g[i][j] == '#' && !st[i][j])
            {
                int cnt = 0,bnd = 0;
                bfs(i,j,cnt,bnd);
                if(cnt == bnd) res ++;
            }
        }
    }
    cout << res;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值