import sys sys.setrecursionlimit(5*10**5) input = sys.stdin.readline from collections import defaultdict, deque, Counter from heapq import heappop, heappush from bisect import bisect_left, bisect_right from math import gcd h,w = map(int,input().split()) a = [list(map(int,input().split())) for i in range(h)] col = [[-1]*(w) for i in range(h)] r = [(a[0][0],0*w+0)] b = [(a[-1][-1],(h-1)*w+(w-1))] dx = [1,-1,0,0] dy = [0,0,1,-1] for i in range(h*w+10): if i % 2 == 0: while r: num, crr = heappop(r) x, y = crr//w, crr%w if col[x][y] == -1: col[x][y] = 1 break for j in range(4): nx = x+dx[j] ny = y+dy[j] if not (0<=nx