import heapq H,W=map(int,input().split()) A=[list(map(int,input().split())) for h in range(H)] color=[[None]*W for h in range(H)] queue=[[(A[0][1],0,1),(A[1][0],1,0)],[(A[H-1][W-2],H-1,W-2),(A[H-2][W-1],H-2,W-1)]] color[0][0]=0 color[H-1][W-1]=1 heapq.heapify(queue[0]) heapq.heapify(queue[1]) seen=[[[False]*W for h in range(H)] for c in range(2)] seen[0][0][1]=1 seen[0][1][0]=1 seen[1][H-1][W-2]=1 seen[1][H-2][W-1]=1 ans=0 while True: c=ans%2 a,h,w=heapq.heappop(queue[c]) ans+=1 color[h][w]=c skip=False for dh,dw in ((0,1),(1,0),(0,-1),(-1,0)): if 0<=h+dh