from heapq import heappop, heappush h, w = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(h)] # くっつくまでやる a_q = [(a[0][0], 0, 0)] b_q = [(a[-1][-1], h - 1, w - 1)] colors = [[-1] * w for _ in range(h)] go = True turn = 0 cnt = 0 DXDY = [(1, 0), (0, 1), (-1, 0), (0, -1)] while go: # print(a_q, b_q, turn) if turn == 0: _, y, x = heappop(a_q) else: _, y, x = heappop(b_q) if colors[y][x] != -1: continue colors[y][x] = turn for dx, dy in DXDY: nx, ny = x + dx, y + dy if 0 <= nx < w and 0 <= ny < h: if colors[ny][nx] == -1: if turn == 0: heappush(a_q, (a[ny][nx], ny, nx)) else: heappush(b_q, (a[ny][nx], ny, nx)) elif colors[ny][nx] != turn: go = False turn = 1 - turn cnt += 1 print(cnt - 2)