from collections import deque def main(): W, H = map(int, input().split()) M = [list(map(int, input().split())) for i in range(H)] Q = deque([(False, 0, 0), (True, 0, 0)]) D = [[[None]*W for i in range(H)] for j in range(2)] D[0][0][0] = D[1][0][0] = 0 while len(Q) > 0: b, x, y = Q.popleft() if (x, y) == (H-1, W-1): print(D[b][x][y]) return for dx, dy in [(-1, 0), (1, 0), (0, 1), (0, -1)]: r, c = x + dx, y + dy if 0 <= r < H and 0 <= c < W and D[not b][r][c] is None: if b and M[x][y] >= M[r][c]: continue if (not b) and M[x][y] <= M[r][c]: continue D[not b][r][c] = D[b][x][y] + 1 Q.append((not b, r, c)) print(-1) return if __name__ == '__main__': main()