h, w = map(int, input().split()) h -= 2 a = [list(map(int, input().split())) for _ in range(h)] INF = 10**18 dp = [[INF] * w for _ in range(h)] + [[INF] * w] for i in range(h): if a[i][0] == -1: continue dp[i][0] = a[i][0] for i in range(w - 1): for j in range(h): if a[i][j + 1] == -1: continue dp[i][j + 1] = min(dp[i - 1][j], dp[i][j], dp[i + 1][j]) + a[i][j + 1] ans=min(v[-1] for v in dp) print(ans if ans < INF else -1) # print(*dp, sep="\n")