#壁の置き方を経路と考える。 #8方向すべてに行くことができる #左端から右端に到達出来たら可能 #すべてのHについて探索する。DFSするのでH*H*W #800**3って通るんすか?通らなそう #ダイクストラ法みたいなことをすればよい? import heapq H,W = map(int,input().split()) A = [list(map(int,input().split())) for i in range(H-2)] queue = [] costs = [[float('inf')]*W for i in range(H-2)] for i in range(H-2): if A[i][0] != -1: costs[i][0] = A[i][0] heapq.heappush(queue,(A[i][0],i,0)) while queue: cost,h,w = heapq.heappop(queue) if cost > costs[h][w]: continue for dh,dw in ((0,1),(1,0),(-1,0),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)): if 0 <= h+dh < H-2 and 0 <= w+dw < W and A[h+dh][w+dw] != -1: temp = costs[h][w] + A[h+dh][w+dw] if temp < costs[h+dh][w+dw]: costs[h+dh][w+dw] = temp heapq.heappush(queue,(temp,h+dh,w+dw)) ans = min([costs[i][-1] for i in range(H-2)]) if ans == float("inf"): print(-1) else: print(ans)