dxy = [(1,0), (-1,0), (0,1), (0,-1)] from heapq import heapify, heappop, heappush H, W = map(int,input().split()) A = [list(map(int,input().split())) for _ in range(H)] visited = [[None for _ in range(W)] for _ in range(H)] visited[0][0] = 0 visited[H-1][W-1] = 1 hq = [[], []] heapify(hq[0]); heapify(hq[1]) for i, xy in enumerate([[0, 0], [H-1, W-1]]): x, y = xy for dx, dy in dxy: _x = x+dx _y = y+dy if (not 0 <= _x < H) or (not 0 <= _y < W): continue heappush(hq[i], [A[_x][_y], _x, _y]) i = 0 while True: ii = i % 2 a, x, y = heappop(hq[ii]) if visited[x][y] != None: continue visited[x][y] = ii for dx, dy in dxy: _x = x+dx _y = y+dy if (not 0 <= _x < H) or (not 0 <= _y < W): continue if visited[_x][_y] == ii: continue if visited[_x][_y] == (ii+1) % 2: exit(print(i+1)) heappush(hq[ii], [A[_x][_y], _x, _y]) i += 1