from heapq import * h, w = map(int, input().split()) A = [list(map(int, input().split())) for _ in range(h)] hq1 = [(A[0][0], 0, 0)] hq2 = [(A[h - 1][w - 1], h - 1, w - 1)] used = [[False] * w for _ in range(h)] used1 = [[False] * w for _ in range(h)] used2 = [[False] * w for _ in range(h)] ans = 0 used1[0][0] = True used2[h - 1][w - 1] = True di = [1, 0, -1, 0] dj = [0, 1, 0, -1] while 1: ans += 1 a, i, j = heappop(hq1) used[i][j] = True for k in range(4): ni, nj = i + di[k], j + dj[k] if ni == -1 or ni == h or nj == -1 or nj == w: continue if not used1[ni][nj]: if used[ni][nj]: print(ans - 2) exit() heappush(hq1, (A[ni][nj], ni, nj)) used1[ni][nj] = True hq1, hq2 = hq2, hq1 used1, used2 = used2, used1