from collections import deque h, w = map(int, input().split()) h -= 2 a = [list(map(int, input().split())) + [-1] for _ in range(h)] + [[-1] * (w + 1)] INF = 10**18 dp = [[INF] * (w + 1) for _ in range(h)] + [[INF] * (w + 1)] que = deque() for i in range(h): if a[i][0] == -1: continue dp[i][0] = a[i][0] que.append((i, 0)) while que: x, y = que.popleft() for i in range(-1, 2): for j in range(-1, 2): sx = x + i sy = y + j if a[sx][sy] != -1 and dp[sx][sy] > dp[x][y] + a[sx][sy]: dp[sx][sy] = dp[x][y] + a[sx][sy] que.append((sx, sy)) ans = min(v[-2] for v in dp) print(ans if ans < INF else -1) # print(*dp, sep="\n")