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)] color = [[-1]*W for _ in range(H)] que = [[(A[-1][-1], H-1, W-1)], [(A[0][0], 0, 0)]] for t in range(-1, H*W-1): while True: a, i, j = heappop(que[t%2]) if color[i][j] == -1: break 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: heappush(que[t%2], (A[ni][nj], ni, nj)) elif color[ni][nj] != t%2: break else: continue print(t); break