'''
5 6
1 0 1 0 1 0
1 1 1 1 1 1
0 0 0 0 0 1
1 1 1 1 1 1
1 1 1 1 1 1
'''

from sys import stdin
from collections import deque

n, m = map(int, stdin.readline().rstrip().split())
arr = []
graph = []

for step in range(n):
    arr.append(list(map(int, stdin.readline().rstrip().split())))

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]


def bfs(x, y):
    queue = deque()
    queue.append((x, y))

    while queue:
        x, y = queue.popleft()

        for step in range(4):
            nx = x + dx[step]
            ny = y + dy[step]

            if nx < 0 or ny < 0 or nx >= n or ny >= m:
                continue

            if arr[nx][ny] == 0:
                continue

            if arr[nx][ny] == 1:
                arr[nx][ny] = arr[x][y] + 1
                queue.append((nx, ny))

    return arr[n - 1][m - 1]


print(bfs(0, 0))