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()) def enc(h, w): return h*W + w def dec(x): return x//W, x%W grid = [] for _ in range(H): grid.append(list(map(int, input().split()))) color = [[-1]*W for _ in range(H)] q = [[(grid[-1][-1], enc(H-1, W-1))], [(grid[0][0], enc(0, 0))]] cnt = -2 while True: while True: _, x = heapq.heappop(q[(cnt-1)%2]) h, w = dec(x) 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], enc(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()