import sys
input=sys.stdin.readline
from collections import deque
col, row = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(row)]
dx = [0,0,1,-1]
dy = [1,-1,0,0]
def find_index(graph, target):
res = deque()
for i in range(row):
for j in range(col):
if graph[i][j] == target:
res.append((i,j))
return res
def bfs(graph,q):
while q:
i,j = q.popleft()
for k in range(4):
x = i+dx[k]
y = j+dy[k]
if 0<=x<row and 0<=y<col and graph[x][y] == 0:
graph[x][y] = graph[i][j] +1
q.append((x,y))
if len(find_index(graph, 0)) == 0: # 처음부터 안익은거 없으면 0출력
print(0)
else:
# 1인 원소 인덱스 찾아서 bfs
q = find_index(graph, 1)
# print(q)
bfs(graph, q)
# for g in graph:
# print(g)
ans = -1
chk = False
for g in graph:
for j in g:
if j ==0:
chk= True
ans = max(ans, j)
if chk: # bfs 이후에도 안익은거 있으면 -1
print(-1)
else:
print(ans-1)
처음 그래프에서 1인 원소의 인덱스(익은 토마토의 인덱스)를 queue에 넣고 bfs
이동할 수 있는 인덱스(x,y)의 값을 현재 인덱스(i,j)의 값 +1 을 해서 방문처리와 날짜세기