백준 - 2573 : 빙산 (G5)

🏷️ python 🏷️ boj

수정일 : 2024-11-15


 1import copy
 2from collections import deque
 3
 4N, M = map(int, input().split())
 5L = [list(map(int, input().split())) for _ in range(N)]
 6L[0][0] = 0
 7L[N-1][M-1] = 0
 8vx = [0, 0, -1, 1]
 9vy = [-1, 1, 0, 0]
10
11def melt(L):
12    L_ = copy.deepcopy(L)
13    for i in range(M):
14        for j in range(N):
15            if L[j][i] != 0:
16                for k in range(4):
17                    nx = j + vx[k]
18                    ny = i + vy[k]
19
20                    if not 0 <= nx < N or not 0 <= ny < M:
21                        continue
22                    if L[nx][ny] == 0 and L_[j][i] != 0:
23                        L_[j][i] -= 1
24    return L_
25
26def check(L):
27    visited = [[False]*M for _ in range(N)]
28    q = deque()
29    c = 0
30
31    for i in range(M):
32        for j in range(N):
33            if L[j][i] != 0 and not visited[j][i]:
34                q.append((j, i))
35                while q:
36                    cx, cy = q.popleft()
37
38                    for k in range(4):
39                        nx = cx + vx[k]
40                        ny = cy + vy[k]
41
42                        if not 0 <= nx < N or not 0 <= ny < M or visited[nx][ny]:
43                            continue
44                        if L[nx][ny] != 0:
45                            visited[nx][ny] = True
46                            q.append((nx, ny))
47                c += 1
48    return c
49
50cnt = 0
51while True:
52    cnt += 1
53    L = melt(L)
54    t = check(L)
55    if t == 0:
56        print (0)
57        break
58    if t >= 2:
59        print (cnt)
60        break
  • 가로세로가 헷갈리면 안되는데.. 큰일이다