# 미로 탐색
from collections import deque
n, m = map(int, input().split())
arr = [list(map(int, input())) for _ in range(n)]
q = deque()
visited = [[0] * m for _ in range(n)]
dist = [[0]*m for _ in range(n)]
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
q.append((0, 0))
visited[0][0] = 1
dist[0][0] = 1
while q:
i, j = q.popleft()
for a in range(4):
ni, nj = i + dx[a], j + dy[a]
if 0 <= ni < n and 0 <= nj < m:
if visited[ni][nj] == 0 and arr[ni][nj] == 1:
q.append((ni, nj))
dist[ni][nj] = dist[i][j] + 1
visited[ni][nj] = 1
print(dist[n-1][m-1])