BOJ 16236: 아기상어

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

  • 2월동안 187문제 풀기(지난달 누적 87개) (33/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
#include <bits/stdc++.h>
using namespace std;

int N, arr[21][21], visit[21][21];
const int dx[4] = {0,0,-1,1};
const int dy[4] = {-1,1,0,0};
inline bool bound(int n) { return n>=0 && n < N; }
struct Point{ int x, y; };
int cx, cy, sz = 2, ate;

void fillInput() {
  cin >> N;
  for(int i =0; i < N; i++)
    for(int j = 0; j < N; j++) {
      cin >> arr[i][j];
      if(arr[i][j] == 9) {
        cx = i, cy = j;
        arr[i][j] = 0;
      }
    }
}

int goEat() {
  queue<Point> q;
  int tt = 0;
  q.push({cx,cy});
  memset(visit, 0, sizeof(visit));
  visit[cx][cy] = 1;
  while(q.size()) {
    tt++;
    int curIter = q.size();
    vector<pair<int,int>> candi;
    for(int ci = 0; ci < curIter; ci++) {
      Point cur = q.front();
      q.pop();
      for(int d = 0; d < 4; d++) {
        int nx = cur.x + dx[d];
        int ny = cur.y + dy[d];
        if(!bound(nx) || !bound(ny) || arr[nx][ny] > sz || visit[nx][ny]) continue;
        if(arr[nx][ny] && arr[nx][ny] < sz) candi.push_back({nx,ny});
        q.push({nx,ny});
        visit[nx][ny] = 1;
      }
    }
    if(candi.size()) {
      sort(candi.begin(), candi.end());
      cx = candi[0].first;
      cy = candi[0].second;
      arr[cx][cy] = 0;
      ate++;
      if(ate == sz) sz++, ate = 0;
      return tt;
    }
  }
  return -1;
}

int main() {
  fillInput();
  int tt = 0, total = 0;
  while((tt = goEat()) != -1)
    total += tt;
  cout << total;
}