import heapq H,W = map(int,input().split()) A = [ list(map(int,input().split())) for i in range(H) ] dic = {} lis = [] for i in range(H): for j in range(W): lis.append( A[i][j] ) lis.sort() for i in range(len(lis)): dic[lis[i]] = i for i in range(H): for j in range(W): A[i][j] = dic[A[i][j]] rev = [0] * (H*W) for i in range(H): for j in range(W): rev[A[i][j]] = (i,j) color = [[-1] * W for i in range(H)] state = [[0] * W for i in range(H)] q0 = [] q1 = [] color[0][0] = 1 q1.append( A[0][0] ) color[H-1][W-1] = 0 q0.append( A[H-1][W-1] ) ans = 0 for i in range(H*W+1): flag = False if i % 2 == 0: num = heapq.heappop(q0) x,y = rev[num] color[x][y] = 0 for xx,yy in ( (x-1,y),(x+1,y),(x,y-1),(x,y+1) ): if not (0 <= xx < H and 0 <= yy < W): continue if state[xx][yy] & 1 == 0: state[xx][yy] |= 1 heapq.heappush( q0 , A[xx][yy]) if color[xx][yy] == 1: flag = True else: num = heapq.heappop(q1) x,y = rev[num] color[x][y] = 1 for xx,yy in ( (x-1,y),(x+1,y),(x,y-1),(x,y+1) ): if not (0 <= xx < H and 0 <= yy < W): continue if state[xx][yy] & 2 == 0: state[xx][yy] |= 2 heapq.heappush( q1 , A[xx][yy]) if color[xx][yy] == 0: flag = True ans += 1 if flag: break print (ans - 3)