import std; void main () { int H, W; readln.read(H, W); int[][] A = new int[][](H-2, 0); foreach (i; 0..H-2) A[i] = readln.split.to!(int[]); solve(H, W, A); } void solve (int H, int W, int[][] A) { /* dijkstraを回す */ int[][] cost = new int[][](H-2, W); BinaryHeap!(Tuple!(int, int, int)[], "b[2] < a[2]") PQ = []; foreach (i; 0..H-2) if (A[i][0] != -1) { PQ.insert(tuple(i, 0, A[i][0])); } foreach (c; cost) c[] = int.max; const int[] dxy = [-1, 0, 1]; bool isInGrid (int y, int x) { return 0 <= y && y < H-2 && 0 <= x && x < W; } while (!PQ.empty) { auto head = PQ.front; PQ.removeFront; if (cost[head[0]][head[1]] < head[2]) continue; cost[head[0]][head[1]] = head[2]; foreach (dy; dxy) foreach (dx; dxy) if (dy != 0 || dx != 0) { int y = head[0] + dy, x = head[1] + dx; if (!isInGrid(y, x)) continue; if (A[y][x] == -1) continue; int NewCost = cost[head[0]][head[1]] + A[y][x]; if (cost[y][x] <= NewCost) continue; cost[y][x] = NewCost; PQ.insert(tuple(y, x, NewCost)); } } int ans = int.max; foreach (i; 0..H-2) ans = min(ans, cost[i][W-1]); if (ans < int.max) { writeln(ans); } else { writeln(-1); } } void read (T...) (string S, ref T args) { auto buf = S.split; foreach (i, ref arg; args) { arg = buf[i].to!(typeof(arg)); } }