import sys
from collections import deque
n , m = map(int, sys.stdin.readline().split())
dx = [0 ,1 , 0, -1]
dy = [1 , 0 ,-1 , 0]
matrix =[[0]*(m+2)]
matrix += [[0]+list(map(int, sys.stdin.readline().rstrip()))+[0] for _ in range(n)]
matrix +=[[0]*(m+2)]
def bfs(startX , startY):
queue=deque([[startX , startY,1]])
while queue:
pop = queue.popleft()
for i in range(4):
nextX = dx[i] + pop[0]
nextY = dy[i] + pop[1]
if(matrix[nextX][nextY] == 1):
queue.append([nextX,nextY, pop[2]+1])
matrix[nextX][nextY] = pop[2]+1
bfs(1,1)
print(matrix[n][m])