import sys
from collections import deque
sys.setrecursionlimit(1500000)
q = deque([(1, 1, 0, 1)])
h, w = map(int, input().split())
TF = True
visit = {}
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
ground = [[-1] * (w + 2)]
for _ in range(h):
ground.append([-1] + list(map(int, input().strip())) + [-1])
ground.append([-1] * (w + 2))
while q:
y, x, k, t = q.popleft()
if y == h and x == w:
print(t)
TF = False
break
if (y, x, k) in visit:
continue
if ground[y][x] != -1:
if ground[y][x] == 0:
for m in range(4):
q.append((y + dy[m], x + dx[m], k, t + 1))
elif k == 0:
k = 1
for m in range(4):
q.append((y + dy[m], x + dx[m], k, t + 1))
visit[(y, x, k)] = True
if TF:
print(-1)



