walk=[ (1,0), (-1,0), (0,1), (0,-1), ] from heapq import heapify,heappop,heappush h,w=map(int,input().split()) a=[list(map(int,input().split())) for i in range(h)] fi=[[-1]*w for i in range(h)] fi[0][0]=0 fi[0][1]=2 fi[1][0]=2 fi[-1][-1]=1 fi[-1][-2]=3 fi[-2][-1]=3 que0=[] que1=[] heappush(que0,(a[0][1],0,1)) heappush(que0,(a[1][0],1,0)) heappush(que1,(a[h-1][w-2],h-1,w-2)) heappush(que1,(a[h-2][w-1],h-2,w-1)) que=[que0,que1] def inside(y,x): return 0<=y