import typing import sys from collections import defaultdict import heapq input = lambda: sys.stdin.readline().strip() inf = 10**18 mod = 998244353 # import pypyjit # pypyjit.set_param('max_unroll_recursion=-1') # sys.setrecursionlimit(10**6) def solve(): H, W = map(int, input().split()) grid = [] for _ in range(H): grid.append(list(map(int, input().split()))) color = [[-1]*W for _ in range(H)] q = [[(grid[-1][-1], H-1, W-1)], [(grid[0][0], 0, 0)]] cnt = -2 while True: while True: _, h, w = heapq.heappop(q[(cnt-1)%2]) if color[h][w] == -1: break cnt += 1 color[h][w] = cnt%2 # 隣あっているマスに異なるいろがあったら終わり for dh, dw in zip([1, 0, -1, 0], [0, 1, 0, -1]): if 0 <= dh + h <= H-1 and 0 <= dw + w <= W-1: if color[dh + h][dw + w]==-1: heapq.heappush(q[cnt%2], (grid[dh+h][dw+w], dh+h, dw+w)) if color[dh + h][dw + w]==(cnt-1)%2: print(cnt) return def main(): t = 1 for _ in range(t): solve() main()