2018年第九届蓝桥杯【C++省赛B组】 第九题——全球变暖(bfs+queue)

标题:全球变暖

你有一张某海域NxN像素的照片,".“表示海洋、”#"表示陆地,如下所示:

.......
.##....
.##....
....##.
..####.
...###.
.......

其中"上下左右"四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。

由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。

例如上图中的海域未来会变成如下样子:

.......
.......
.......
.......
....#..
.......
.......

请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。

【输入格式】
第一行包含一个整数N。 (1 <= N <= 1000)
以下N行N列代表一张海域照片。

照片保证第1行、第1列、第N行、第N列的像素都是海洋。

【输出格式】
一个整数表示答案。

【输入样例】

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

【输出样例】
1

思路:

遍历整个图中的岛屿,对于每一个岛屿进行bfs并标记会被淹没的部分

bfs过程:运用队列依次遍历没有遍历过和没有越界的点。并对于相邻地方有海的点则标记将会被淹没。如果被标记的将会被淹没的点等于岛上的点则它会被淹没。

 

代码:

#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
const int maxn = 1005;
typedef pair<int,int> PII;
queue<PII> q;
char a[maxn][maxn];
int state[maxn][maxn];
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
int n;
int ans = 0;
void bfs(int x,int y){
    int will_flood = 0,flood = 0,cnt = 0;
    while(!q.empty()) q.pop();
    state[x][y] = 1;
    q.push({x,y});
    while(q.size()){
        cnt++;
        PII t = q.front();
        q.pop();
        for(int i=0;i<4;i++){
            int xx = t.first+dx[i];
            int yy = t.second+dy[i];
            if(state[xx][yy]||xx<0||xx>=n||yy<0||yy>=n)
                continue;
            if(a[xx][yy] == '.'){
                flood++;
            }
            else{
                state[xx][yy]  =1;
                q.push({xx,yy});
            }
        }
        if(flood>0){
            will_flood++;
            flood = 0;
        }
    }    
    if(will_flood==cnt){
        ans++;
    }
    
}
int main(){
    cin>>n;
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cin>>a[i][j];
            state[i][j] = 0;
        }
    }
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            if(a[i][j]=='#'&&!state[i][j])
                bfs(i,j);
        }
    }
    cout<<ans<<endl;
    return 0;
}

 

posted @ 2020-09-29 14:22  sqsq  阅读(194)  评论(0编辑  收藏  举报