from heapq import heappop,heappush H,W = map(int,input().split()) G = [] color = [] for i in range(H): G.append(list(map(int,input().split()))) color.append([-1]*W) now1 = (0,0) now2 = (H-1,W-1) Q1,Q2 = [],[] heappush(Q1,(G[0][0],0,0)) heappush(Q2,(G[H-1][W-1],H-1,W-1)) cnt = 0 dir = [(-1,0),(1,0),(0,-1),(0,1)] while True: if cnt % 2 == 0: if Q1: val,h,w = heappop(Q1) if color[h][w] != -1: continue color[h][w] = 0 cnt += 1 for a,b in dir: if 0 <= h+a < H and 0 <= w+b < W: if color[h+a][w+b] == 1: print(cnt-2) exit() elif color[h+a][w+b] == -1: heappush(Q1,(G[h+a][w+b],h+a,w+b)) else: print(cnt-2) exit() else: if Q2: val,h,w = heappop(Q2) if color[h][w] != -1: continue color[h][w] = 1 cnt += 1 for a,b in dir: if 0 <= h+a < H and 0 <= w+b < W: if color[h+a][w+b] == 0: print(cnt-2) exit() elif color[h+a][w+b] == -1: heappush(Q2,(G[h+a][w+b],h+a,w+b)) else: print(cnt-2) exit()