1인 부분을 찾아서 각 지점을 큐애 넣어서 bfs를 돌린다
from collections import deque
m,n = map(int, input().split())
graph = []
for i in range(n):
graph.append(list(map(int,input().split(sep=" "))))
dx = [-1,1,0,0]
dy = [0,0,-1,1]
def tomato():
queue = deque()
for i in range(n):
for j in range(m):
if graph[i][j] == 1:
queue.append((i,j))
while queue:
x, y = queue.popleft()
weight = 0
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx >= n or ny >= m or nx < 0 or ny < 0:
continue
if graph[nx][ny] == -1:
continue
if graph[nx][ny] == 0:
graph[nx][ny] += graph[x][y] + 1
queue.append((nx,ny))
weight += 1
return graph[n-1][m-1]
tomato()
max = 0
is_zero = False
for i in range(n):
for j in range(m):
if max < graph[i][j]:
max = graph[i][j]
if graph[i][j] == 0:
is_zero = True
if is_zero == True:
print(-1)
else:
print(max-1)