https://www.acmicpc.net/problem/7576
import sys
from collections import deque
m, n = map(int, sys.stdin.readline().split())
box = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
queue = deque([])
for i in range(n):
for j in range(m):
if box[i][j] == 1:
queue.append((i, j))
def tomato():
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m:
if box[nx][ny] == -1:
continue
if box[nx][ny] == 0:
queue.append((nx, ny))
box[nx][ny] = box[x][y] + 1
tomato()
flag = False
for i in range(n):
for j in range(m):
if box[i][j] == 0:
flag = True
break
res = max(map(max, box))
if flag == True:
print(-1)
elif res == 1:
print(0)
else:
print(res - 1)