import sys
from collections import deque
n,m = map(int, sys.stdin.readline().split())
maze = []
distanceA = [[0 for _ in range(1010)] for _ in range(1010)]
distanceB = [[0 for _ in range(1010)] for _ in range(1010)]
check =[[False for _ in range(1010)] for _ in range(1010)]
for i in range(n):
maze.append(list(map(int, sys.stdin.readline().split())))
def bfs(a,b,distance):
q = deque()
q.append((a,b))
check[a][b] = True
dx=[0,0,-1,1]
dy=[1,-1,0,0]
while q:
x,y=q.popleft()
for i in range(4):
nx = x+dx[i]
ny = y+dy[i]
if 0<=nx<n and 0<=ny<m and check[nx][ny]==False:
distance[nx][ny] = distance[x][y] +1
check[nx][ny]=True
if maze[nx][ny] == 0:
q.append((nx,ny))
bfs(n-1,0,distanceA)
check =[[0 for _ in range(1010)] for _ in range(1010)]
bfs(0,m-1,distanceB)
result = 1000010
for i in range(n):
for j in range(m):
if maze[i][j] >0 and distanceB[i][j]>0 and distanceA[i][j]>0:
result = min(result, distanceA[i][j]+distanceB[i][j])
print(result)