H,W = map(int,input().split()) A = [list(map(int,input().split())) for _ in range(H)] dat = [[-1] * W for _ in range(H)] #dat[0][0] = 1 #dat[-1][-1] = 0 import heapq import sys o = [(A[0][0],0,0)] e = [(A[-1][-1],H-1,W-1)] ans = 0 for _ in range(1,H * W+1): if _ % 2 == 0: q = e j = 0 else: q = o j = 1 while q: a,x,y = heapq.heappop(q) if dat[x][y] != -1:continue else:break dat[x][y] = j #print(x,y) ans += 1 for u,v in [(0,-1),(0,1),(1,0),(-1,0)]: if 0 <= x + u < H and 0 <= y + v < W: k = dat[x + u][y + v] if k == 1 - j: print(ans - 2) exit() elif k == -1: heapq.heappush(q,(A[x + u][y + v],x + u,y + v))