2018 Blue Bridge Cup Provincial C/C++ Group B - Global Warming

Topic

You have a NxN pixel photo of a sea area, "." for ocean and "#" for land, like this:
 ….
.##….
.##….
 ….##.
..#### . .
. . . . . . . .
. .
Among them, a piece of land connected in four directions "up, down, left, and right" forms an island. For example, there are 2 islands in the picture above.
Due to rising sea levels caused by global warming, scientists predict that a pixel of the edge of the island will be submerged by sea water in the next few decades. Specifically, if a land pixel is adjacent to an ocean (there are oceans in four adjacent pixels up, down, left, and right), it will be submerged.
For example, the sea area in the picture above will look like this in the future:
…….
…….
…….
…….
….#..
…….
…….
Please calculate: According to the prediction of scientists, how many islands are there in the picture will be completely submerged.

input format

The first line contains an integer N. (1 <= N <= 1000)
The following N rows and N columns represent a sea area photo.
The photo guarantees that the pixels in row 1, column 1, row N, and column N are all oceans.

output format

An integer representing the answer.

input sample

7
…….
.##….
.##….
….##.
..####.
…###.
…….

Sample output

1

answer

Just perform dfs directly, count the total number of islands, count the number of islands that will not be submerged, and the difference is what we require.

code

#include<iostream>
using namespace std;
const int N = 1010char a[N][N];
int d[][2] = {0 , 1 , 0 , -1 , 1 , 0 , -1 , 0};
int n;
int ans = 0;
int ans_island = 0;

void dfs(int x , int y){
    if(a[x][y] != '#'){
        return;
    }
    if(x < 1 || x > n || y < 1 || y > n){
        return ;
    }
    if(!flag){
        int cnt = 0;
        for(int i = 0;i < 4;i++){
            int dx = x + d[i][0];
            int dy = y + d[i][1];
            if(dx > 0 && dx <= n && dy > 0 && dy <= n && a[dx][dy] != '.'){
                cnt++;
            }
            if(cnt == 4){
                ans++;
                flag = true;
            }
        }
    }
    a[x][y] = '*';
    for(int i = 0;i < 4;i++){
        int dx = x + d[i][0];
        int dy = y + d[i][1];
        if(dx > 0 && dx <= n && dy > 0 && dy <= n && a[dx][dy] != '.'){
            dfs(dx , dy);
        }
    }
}

int main(){
    cin >> n;
    for(int i = 1;i <= n;i++){
        for(int j = 1;j <= n;j++){
            cin >> a[i][j];
        }
    }
    for(int i = 1; i <= n;i++){
        for(int j = 1;j <= n;j++){
            if(a[i][j] == '#'){
                ans_island++;
                flag = false;
                dsf(i , j);
            }
        }
    }
    cout << ans_island - ans << endl;
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324508228&siteId=291194637