https://www.acmicpc.net/problem/2573
from collections import deque
import sys
input = sys.stdin.readline
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
def bfs(i, j):
que = deque()
que.append((i, j))
visited[i][j] = True
while que:
x, y = que.popleft()
temp = 0
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == False:
if ice[nx][ny] == 0:
temp += 1
else:
que.append((nx, ny))
visited[nx][ny] = True
ice[x][y] -= temp
if ice[x][y] < 0:
ice[x][y] = 0
return 1
n, m = map(int, input().split())
ice = []
for _ in range(n):
ice.append(list(map(int, input().split())))
cnt = 0
while True:
visited = [[False] * m for _ in range(n)]
res = 0
temp = 0
for i in range(n):
for j in range(m):
if ice[i][j] != 0 and visited[i][j] == False:
res += bfs(i, j)
elif ice[i][j] == 0:
temp += 1
if temp == n*m:
break
if res >= 2:
break
cnt += 1
if temp == n * m:
print(0)
else:
print(cnt)
BFS를 이용해서 풀면 된다.