BOJ 2573: 빙산

https://www.acmicpc.net/problem/2573

  • 2월동안 187문제 풀기(지난달 누적 87개) (29/187)
  • 어느정도 익숙해져서 잘 풀지만, 결국 또 조건을 잘 안읽어서 바운드 컨디션 체크 못함.
  • 문제를 읽자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <bits/stdc++.h>
using namespace std;

int N, M, tt, cnt;
vector<vector<int>> arr, visit;
const int dx[4] = {0,0,1,-1};
const int dy[4] = {1,-1,0,0};

inline bool bound(int x, int y) {
  return x >= 0 && x < N && y >= 0 && y < M;
}

void melt() {
  auto orig = arr;
  int nCnt = 0;
  for(int x = 0; x < N; x++) {
    for(int y = 0; y < M; y++) {
      for (int d = 0; arr[x][y] && d < 4; d++) {
        int nx = x + dx[d];
        int ny = y + dy[d];
        if(!bound(nx,ny)) continue;
        arr[x][y] -= (orig[nx][ny] == 0);
      }
      if(arr[x][y]) nCnt++;
    }
  }
  cnt = nCnt;
}

int dfs(int x, int y) {
  int ret = 1;
  visit[x][y] = 1;
  for(int d = 0; d < 4; d++) {
    int nx = x + dx[d];
    int ny = y + dy[d];
    if(!bound(nx,ny) || visit[nx][ny] || !arr[nx][ny]) continue;
    ret += dfs(nx,ny);
  }
  return ret;
}

int check() {
  visit = vector<vector<int>>(N, vector<int>(M));
  for(int i = 0; i < N; i++) {
    for(int j = 0; j < M; j++) {
      if(arr[i][j])
        return dfs(i,j);
    }
  }
  return 0;
}

int main() {
  scanf("%d %d", &N, &M);
  arr.resize(N, vector<int>(M));
  for(int i = 0; i < N; i++)
    for(int j = 0; j < M; j++) {
      scanf("%d", &arr[i][j]);
      if(arr[i][j]) cnt++;
    }

  for(tt = 0; cnt && check() == cnt ; tt++)
    melt();
  printf("%d", cnt ? tt : 0);
}