# Topic : Graph _ 미로 탐색
#
# Python 3 : 104ms

from collections import deque
import sys
# graph[N-1][M-1]에 도달하는 여러가지 경우에 수가 존재하지만 이경우 queue에서 이동거리가 가장 짧은 순으로 비교가 진행되므로 
# 이동거리가 가장 짧은 동선으로 이동하여 (N, M)에 도착했을 때 

def bfs(x,y):
  dx = [-1,1,0,0]
  dy = [0,0,-1,1]

  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] == 1: # 이경우 주의해서 생각해야하는것이 어떤 다른 경로로 벌써 update(graph[x][y]+1)이 된 경우에는 1이 아니므로 가장 먼저 해당 지점을 방문한 루트의 값이 graph[nx][ny]의 값이 된다.
        graph[nx][ny] = graph[x][y] + 1
        queue.append((nx,ny))

  return graph[N-1][M-1]  

N , M = map(int,sys.stdin.readline().split())

graph = []
for _ in range(N):
  str = sys.stdin.readline().rstrip()
  graph.append([int(s) for s in str])

print(bfs(0,0))