from collections import * W, H = map(int, input().split()) M = [] for i in range(H): M.append(list(map(int, input().split()))) inf = 10 ** 18 dist = defaultdict(lambda:inf) Q = deque() if M[1][0] != M[0][0]: dist[(1, 0, 0, 0)] = 1 Q.append([1, 0, 0, 0]) if M[0][1] != M[0][0]: dist[(0, 1, 0, 0)] = 1 Q.append([0, 1, 0, 0]) def kadomatsu(a, b, c): S = set([a, b, c]) if len(S) != 3: return False if b > a and b > c: return True if b < a and b < c: return True return False dx = [1, 0, -1, 0] dy = [0, 1, 0, -1] while Q: x, y, px, py = Q.popleft() for k in range(4): nx = x + dx[k] ny = y + dy[k] if nx < 0 or nx > H - 1 or ny < 0 or ny > W - 1: continue if dist[(nx, ny, x, y)] != inf: continue if kadomatsu(M[px][py], M[x][y], M[nx][ny]): dist[(nx, ny, x, y)] = dist[(x, y, px, py)] + 1 Q.append([nx, ny, x, y]) ans = min(dist[(H - 1, W - 1, H - 2, W - 1)], dist[(H - 1, W - 1, H - 1, W - 2)]) print(ans) if ans != inf else print(-1)