from heapq import * EMPTY = -1 H, W = map(int, input().split()) nums = [list(map(int, input().split())) for _ in range(H)] cols = [[EMPTY] * W for _ in range(H)] cols[0][0] = 0 cols[H - 1][W - 1] = 1 q0 = [(nums[0][1], (0, 1)), (nums[1][0], (1, 0))] heapify(q0) q1 = [(nums[H - 1][W - 2], (H - 1, W - 2)), (nums[H - 2][W - 1], (H - 2, W - 1))] heapify(q1) Q = [q0, q1] dirs = [[0, 1], [1, 0], [-1, 0], [0, -1]] dipper = 0 for i in range(0,1000): i2 = i % 2 a, (x, y) = heappop(Q[i2]) dipper += 1 if cols[x][y] == EMPTY: cols[x][y] = i2 for xd, yd in dirs: x2 = x + xd y2 = y + yd if 0 <= x2 < H and 0 <= y2 < W: if cols[x2][y2] == i2 ^ 1: print(dipper) exit() elif cols[x2][y2] == EMPTY: heappush(Q[i2], (nums[x2][y2], (x2, y2)))