1+ import sys
2+ from collections import deque
3+ input = sys .stdin .readline
4+
5+ # 이차원 배열의 행과 열 개수 입력
6+ n , m = map (int , input ().split ())
7+
8+ # 빙산 높이 정보를 저장할 2차원 배열 생성
9+ iceberg = [list (map (int , input ().split ())) for _ in range (n )]
10+
11+ # 빙산 높이 감소를 계산하는 함수
12+ def get_iceberg_height (iceberg ):
13+ # 감소된 빙산 높이를 저장할 새로운 배열 초기화
14+ new_height = [[0 ] * m for _ in range (n )]
15+ for i in range (n ):
16+ for j in range (m ):
17+ if iceberg [i ][j ] > 0 : # 빙산이 있는 칸만 처리
18+ water_count = 0 # 인접한 바다 칸 개수 초기화
19+
20+ # 상하좌우 네 방향 탐색
21+ for dx , dy in [(- 1 , 0 ), (1 , 0 ), (0 , - 1 ), (0 , 1 )]:
22+ ni , nj = i + dx , j + dy
23+ if 0 <= ni < n and 0 <= nj < m and iceberg [ni ][nj ] == 0 :
24+ water_count += 1
25+
26+ # 바다에 접한 개수만큼 빙산 높이를 감소시키며 최소 0으로 유지
27+ new_height [i ][j ] = max (iceberg [i ][j ] - water_count , 0 )
28+ return new_height
29+
30+ # BFS를 통해 빙산 덩어리 수를 계산하는 함수
31+ def count_icebergs (iceberg ):
32+ visited = [[False ] * m for _ in range (n )] # 방문 여부를 기록할 배열 초기화
33+ iceberg_count = 0 # 빙산 덩어리 수 초기화
34+
35+ for i in range (n ):
36+ for j in range (m ):
37+ # 빙산이 있고 아직 방문하지 않은 경우 새로운 덩어리로 간주
38+ if iceberg [i ][j ] > 0 and not visited [i ][j ]:
39+ iceberg_count += 1
40+ # BFS로 연결된 빙산을 모두 방문 처리
41+ queue = deque ([(i , j )])
42+ visited [i ][j ] = True
43+ while queue :
44+ x , y = queue .popleft ()
45+ for dx , dy in [(- 1 , 0 ), (1 , 0 ), (0 , - 1 ), (0 , 1 )]:
46+ nx , ny = x + dx , y + dy
47+ # 빙산이 연결된 인접 노드를 방문 처리
48+ if 0 <= nx < n and 0 <= ny < m and not visited [nx ][ny ] and iceberg [nx ][ny ] > 0 :
49+ visited [nx ][ny ] = True
50+ queue .append ((nx , ny ))
51+ return iceberg_count
52+
53+ # 연도(시간) 초기화
54+ year = 0
55+
56+ # 빙산이 분리될 때까지 반복
57+ while True :
58+ year += 1
59+
60+ # 빙산 높이 감소 계산 및 업데이트
61+ iceberg = get_iceberg_height (iceberg )
62+
63+ # 현재 빙산 덩어리 수 계산
64+ mountain = count_icebergs (iceberg )
65+
66+ # 빙산 덩어리가 2개 이상으로 분리된 경우
67+ if mountain >= 2 :
68+ print (year )
69+ exit (0 )
70+
71+ # 빙산이 모두 녹아 덩어리가 없는 경우
72+ if mountain == 0 :
73+ print (0 )
74+ exit (0 )
0 commit comments