
def bfs(x,y):
#큐를 생성
queue = deque()
#큐에 시작 노드 넣기
queue.append((x,y))
while queue:
#큐에서 맨 밑 노드 팝
x,y = queue.popleft()
#상하좌우 탐색
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
#범위를 넘어갈 때
if nx < 0 or nx >= n or ny < 0 or ny >= m:
continue
#이동할 수 없는 칸 일 때
if graph[nx][ny] == 0:
continue
#처음 방문하는 칸일때만 +1을 해줌
if graph[nx][ny] == 1:
#최소경로에 1을 더해줘서 갱신
graph[nx][ny] = graph[x][y] + 1
queue.append((nx,ny))
return graph[n-1][m-1]
from collections import deque
n, m = map(int,input().split())
graph = []
for i in range(n):
graph.append(list(map(int,input())))
dx = [-1, 1, 0 , 0]
dy = [0, 0, -1 , 1]
print(bfs(0,0))