2018蓝桥杯C++A组——全球变暖

问题描述

【题目描述】
在这里插入图片描述
【输入】
在这里插入图片描述
【输出】
在这里插入图片描述
【样例输入】

7 
.......
.##....
.##....
....##.
..####.
...###.
.......  

【样例输出】

1

题目解析

这道题可以理解成连通块问题。针对每一个连通块采用 b f s bfs bfs遍历方法动态模拟淹没的过程。

准备 d a t a [ ] data[] data[]数组记录地图数据, m a r k [ ] mark[] mark[]数组标记是否访问过。

双重循环遍历 d a t a [ ] data[] data[]数组当 d a t a [ ] = = # data[]==\# data[]==# m a r k [ ] = = 0 mark[]==0 mark[]==0时就调用 b f s ( ) bfs() bfs()宽度优先遍历四周的岛屿。

具体代码如下:

C++代码

#include<bits/stdc++.h>
using namespace std;
int N,ans; //规模,答案
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
char data[1000][1000];
int mark[1000][1000];
struct Point
{
    int x,y;
};
void bfs(int i,int j)
{
    mark[i][j] = 1;//标记为已访问
    queue<Point> q; //新建一个队列
    q.push({i,j}); //将当前格子封装到Point中并插入队列
    int cnt1=0,cnt2=0; //分别记录当前这个连通块#的数量以及和.相邻的#的数量
    while(!q.empty())
    {
        Point first = q.front();
        q.pop();
        cnt1++;
        bool swed = false; //标记弹出的#四周是否有.
        for(int k=0;k<4;k++) //向四周探测
        {
            int x = first.x+dx[k];
            int y = first.y+dy[k];
            if(x>=0&&x<N&&y>=0&&y<N&&data[x][y]=='.') swed = true;
            //周边的#如果未被访问将其加入队列
            if(x>=0&&x<N&&y>=0&&y<N&&data[x][y]=='#'&&mark[x][y]==0)
            {
                q.push({x,y});
                mark[x][y]=1;
            }
        }
        if(swed) cnt2++;
    }
    //一个连通块就被访问完毕,#的数量记录在cnt1,周边有.的数量记录在cnt2
    if(cnt1==cnt2) ans++;
}
void work()
{
    std::ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>N; //读取规模
    char next; //读换行符
    cin.get(next);
    while(next!='\n') cin.get(next);
    for(int i=0;i<N;i++) //双循环读地图数据
    {
        for(int j=0;j<N;j++)
            cin.get(data[i][j]);
        cin.get(next);
        while(next!='\n') cin.get(next);
    }
    for(int i=0;i<N;i++) //从#开始宽度优先搜索
        for(int j=0;j<N;j++)
            if(mark[i][j]==0&&data[i][j]=='#')
                bfs(i,j);
    cout<<ans<<endl;
}
int main()
{
    work();
    return 0;
}

结果

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芷汀若静

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值