from collections import defaultdict, deque def neighbors4(r: int, c: int) -> list[tuple[int, int]]: res = [] for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]: nr = r + dr nc = c + dc if not (0 <= nr < H and 0 <= nc < W): continue res.append((nr, nc)) return res def is_kadomatu(a, b, c) -> bool: if a == c: return False if a < b > c: return True if a > b < c: return True return False INF = 1 << 62 W, H = map(int, input().split()) G = [] for _ in range(H): G.append(list(map(int, input().split()))) used = set() dists = defaultdict(lambda: INF) q = deque([ (1, 1, 0, G[0][0]), (1, 0, 1, G[0][0]) ]) while q: step, r, c, x = q.popleft() if r == H-1 and c == W-1: print(step) break if (r, c, x) in used: continue used.add((r, c, x)) for nr, nc in neighbors4(r, c): if is_kadomatu(G[nr][nc], G[r][c], x): q.append((step+1, nr, nc, G[r][c])) else: print(-1)