from heapq import heappop, heappush DIJ = [(-1, 0), (0, -1), (0, 1), (1, 0)] H, W = map(int, input().split()) A = [list(map(int, input().split())) for _ in range(H)] IJ = {A[i][j]: (i, j) for i in range(H) for j in range(W)} color = [[-1]*W for _ in range(H)] que = [[A[-1][-1]], [A[0][0]]] for t in range(-1, H*W-1): i, j = IJ[heappop(que[t%2])] color[i][j] = t%2 for ni, nj in DIJ: ni += i; nj += j if not H > ni >= 0 <= nj < W: continue if color[ni][nj] == -1 or color[ni][nj] == t%2-3: color[ni][nj] -= t%2+1 heappush(que[t%2], A[ni][nj]) elif color[ni][nj] == 1-t%2: break else: continue print(t); break