H,W = map(int,input().split()) A = [list(map(int,input().split())) for i in range(H)] dij = [(0,1),(1,0),(0,-1),(-1,0)] import heapq C = [[-1]*W for _ in range(H)] C[0][0] = 1 C[H-1][W-1] = 0 hq1 = [] hq0 = [] for di,dj in dij: ni = 0 + di nj = 0 + dj if 0 <= ni < H and 0 <= nj < W: heapq.heappush(hq1, (A[ni][nj],ni*W+nj)) for di,dj in dij: ni = H-1 + di nj = W-1 + dj if 0 <= ni < H and 0 <= nj < W: heapq.heappush(hq0, (A[ni][nj],ni*W+nj)) added0 = [[0]*W for _ in range(H)] added1 = [[0]*W for _ in range(H)] for k in range(H*W+1): if k%2==0: while hq1: a,v = heapq.heappop(hq1) i,j = divmod(v,W) if C[i][j] != -1: continue C[i][j] = 1 for di,dj in dij: ni = i + di nj = j + dj if 0 <= ni < H and 0 <= nj < W: if C[ni][nj] == 0: print(k+1) exit() if C[ni][nj] == -1 and added1[ni][nj] == 0: heapq.heappush(hq1, (A[ni][nj],ni*W+nj)) added1[ni][nj] = 1 break else: while hq0: a,v = heapq.heappop(hq0) i,j = divmod(v,W) if C[i][j] != -1: continue C[i][j] = 0 for di,dj in dij: ni = i + di nj = j + dj if 0 <= ni < H and 0 <= nj < W: if C[ni][nj] == 1: print(k+1) exit() if C[ni][nj] == -1 and added0[ni][nj] == 0: heapq.heappush(hq0, (A[ni][nj],ni*W+nj)) added0[ni][nj] = 1 break