求助60分

P8662 [蓝桥杯 2018 省 AB] 全球变暖

Lucashuang @ 2024-09-22 14:18:31

#include<bits/stdc++.h>
using namespace std;
char image[10010][10010] , ima[10010][10010];
int n , m , cnt;
void dfs(int a , int b){
    image[a][b] = '.';
    if(a - 1 > 0 and image[a - 1][b] == '#'){
        dfs(a - 1 , b);
    }
    if(a + 1 <= m and image[a + 1][b] == '#'){
        dfs(a + 1 , b);
    }
    if(b + 1 <= n and image[a][b + 1] == '#'){
        dfs(a , b + 1);
    }
    if(b - 1 > 0 and image[a][b - 1] == '#'){ 
        dfs(a , b - 1);
    }
}
void dfs1(int a , int b){
    ima[a][b] = '.';
    if(a - 1 > 0 and ima[a - 1][b] == '#'){
        dfs(a - 1 , b);
    }
    if(a + 1 <= m and ima[a + 1][b] == '#'){
        dfs(a + 1 , b);
    }
    if(b + 1 <= n and ima[a][b + 1] == '#'){
        dfs(a , b + 1);
    }
    if(b - 1 > 0 and ima[a][b - 1] == '#'){ 
        dfs(a , b - 1);
    }
}
int main(){
    cin >> m;
    n = m;
    for(int i = 1; i <= m; i++){
        for(int j = 1; j <= n; j++){
            cin >> image[i][j];
            ima[i][j] = image[i][j];
        }
    }
    for(int i = 1; i <= m; i++){
        for(int j = 1; j <= n; j++){
            if(image[i][j] == '#'){
                cnt++;
                dfs(i , j);
            }
        }
    }
    for(int i = 1; i <= m; i++){
        for(int j = 1; j <= n; j++){
            if(ima[i][j] == '.'){
                image[i][j] = '.';
            }
            if(ima[i - 1][j] == '.' or ima[i][j - 1] == '.' or ima[i + 1][j] == '.' or ima[i][j + 1] == '.'){
                image[i][j] = '.';
            } else {
                image[i][j] = '#';
            }
        }
    }
    int cnt1 = 0;
    for(int i = 1; i <= m; i++){
        for(int j = 1; j <= n; j++){
            if(image[i][j] == '#'){
                cnt1++;
                dfs1(i , j);
            }
        }
    }
    int ans = cnt - cnt1;
    if(ans < 0) ans = 0;
    cout << ans;
}

|