h,w=map(int,input().split()) a=[list(map(int,input().split())) for i in range(h)] v=[[0]*w for i in range(h)] v[0][0]=1 v[h-1][w-1]=2 from heapq import heappush,heappop q1=[] heappush(q1,(a[1][0],1,0)) heappush(q1,(a[0][1],0,1)) q2=[] heappush(q2,(a[h-2][w-1],h-2,w-1)) heappush(q2,(a[h-1][w-2],h-1,w-2)) for i in range(1,h*w+1): if i%2: while len(q1)>0 and v[q1[0][1]][q1[0][2]]!=0: heappop(q1) if len(q1)==0: print(i-1) exit() z,x,y=heappop(q1) v[x][y]=1 dx,dy=1,0 for _ in range(4): xx,yy=x+dx,y+dy dx,dy=-dy,dx if 0<=xx0 and v[q2[0][1]][q2[0][2]]!=0: heappop(q2) if len(q2)==0: print(i-1) exit() z,x,y=heappop(q2) v[x][y]=2 dx,dy=1,0 for _ in range(4): xx,yy=x+dx,y+dy dx,dy=-dy,dx if 0<=xx