빙산이 녹아서 변한 빙산 높이를 바로 graph에 적용하면 안된다.
import sys
from collections import deque
from itertools import product
input = sys.stdin.readline
def bfs(s_x, s_y):
global graph, visited, new_graph
q = deque([[s_x, s_y]])
dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]
while q:
x, y = q.popleft()
if not visited[x][y]:
visited[x][y] = True
water_cnt = 0
for i, j in zip(dx, dy):
n_x, n_y = x+i, y+j
if graph[n_x][n_y]:
q.append([n_x, n_y])
else:
water_cnt += 1
new_graph[x][y] = graph[x][y] - water_cnt if graph[x][y] >= water_cnt else 0
if __name__ == '__main__':
N, M = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(N)]
years = 0
while True:
visited = [[False for _ in range(M)] for _ in range(N)]
new_graph = [[0 for _ in range(M)] for _ in range(N)]
bfs_cnt = 0
for s_x, s_y in product(range(N), range(M)):
if graph[s_x][s_y] and not visited[s_x][s_y]:
bfs(s_x, s_y)
bfs_cnt += 1
graph = new_graph
if bfs_cnt == 0:
print(0)
exit()
elif bfs_cnt > 1:
print(years)
exit()
years += 1