#MMA Contest 015 G ''' DPみを感じる。こちらのほうが解きやすい・・・のか? 単に状態をもったDPをしたらTLEするに決まっている。 大胆予想: 左から右に王将の要領で移動する。右端にたどり着く最小コストを求めよ。 ''' import heapq as hq import sys f=lambda:list(map(int,input().split())) H,W=f(); A=[[-1]*(W+1)]+[f()+[-1] for _ in range(H-2)]+[[-1]*(W+1)] Q=[]; cost=[[10**9]*W for _ in range(H)] for h in range(1,H-1): hq.heappush(Q,(A[h][0],h,0)) if A[h][0]>=0 else None while Q: dist,h,w=hq.heappop(Q) if dist>cost[h][w]: continue if w==W-1: print(dist); sys.exit() cost[h][w]=dist for x,y in [(-1,0),(1,0),(0,-1),(0,1),(-1,-1),(-1,1),(1,-1),(1,1)]: if A[h+x][w+y]>=0 and cost[h+x][w+y]>dist+A[h+x][w+y]: cost[h+x][w+y]=dist+A[h+x][w+y]; hq.heappush(Q,(dist+A[h+x][w+y],h+x,w+y)) ans=min(cost[h][-1] for h in range(H)) print(ans) if ans<10**9 else print(-1)