알고리즘과 자료구조/백준

BOJ 2573 빙산

bggbr 2019. 12. 24. 11:51
#include <iostream>
#include <string.h>
using namespace std;
#define MAX 301
const int dy[4] = {-1, 1, 0, 0};
const int dx[4] = {0, 0, -1, 1};
int n, m;
int map[MAX][MAX];
int delMap[MAX][MAX];
bool check[MAX][MAX];
int totalLand, totalYear;

bool checkLand(){
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            if(map[i][j]) return true;
        }
    }
    return false;
}

void bfs(int y, int x){
    for(int i = 0; i < 4; i++){
        int ny = y + dy[i];
        int nx = x + dx[i];
        if(ny >= 0 && ny < n && nx >= 0 && nx < m){
            if(map[ny][nx] == 0){
                delMap[y][x]++;
            }
        }
    }
}

void dfs(int y, int x){
    for(int i = 0; i < 4; i++){
        int ny = y + dy[i];
        int nx = x + dx[i];
        if(ny >= 0 && ny < n && nx >= 0 && nx < m){
            if(map[ny][nx] && !check[ny][nx]){
                check[ny][nx] = true;
                dfs(ny, nx);
            }
        }
    }
}

int main(void){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    cin >> n >> m;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            cin >> map[i][j];
        }
    }
    while(1){
        memset(delMap, 0, sizeof(delMap));
        memset(check, 0, sizeof(check));
        //check
        totalLand = 0;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(map[i][j] && check[i][j] == 0){
                    check[i][j] = true;
                    dfs(i, j);
                    totalLand++;
                }
            }
        }
        // 땅이 2개 거나 모든 땅이 0인 경우 break
        if(totalLand >= 2){
            break;
        }else if(!checkLand()){
            totalYear = 0;
            break;
        }
        // bfs
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(map[i][j]){
                    bfs(i, j);
                }
            }
        }
        // melt
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                map[i][j] -= delMap[i][j];
                if(map[i][j] < 0) map[i][j] = 0;
            }
        }
        totalYear++;
    }
    cout << totalYear;
}

'알고리즘과 자료구조 > 백준' 카테고리의 다른 글

BOJ 1389 케빈 베이컨의 6단계 법칙  (0) 2019.12.27
BOJ 1012 유기농 배추  (0) 2019.12.24
BOJ 15649 N과 M (1), 순열  (0) 2019.11.21
BOJ 15650 N과 M (2), 조합  (0) 2019.11.21
BOJ 15651 N과 M (3), 중복 순열  (0) 2019.11.21