#include using namespace std; using ll = long long; int main(){ ios::sync_with_stdio(false); cin.tie(0); int h, w; cin >> h >> w; h -= 2; ll INF = 1ll << 60; vector> A(h, vector(w)), B(h, vector(w, 1ll << 60)); for(int y = 0; y < h; y++){ for(int x = 0; x < w; x++){ cin >> A[y][x]; if(A[y][x] == -1) A[y][x] = INF; } } priority_queue, vector>, greater>> pq; for(int y = 0; y < h; y++){ pq.emplace(A[y][0], y, 0); B[y][0] = A[y][0]; } while(!pq.empty()){ ll d; int y, x; tie(d, y, x) = pq.top(); pq.pop(); if(d > B[y][x]) continue; for(int dy = -1; dy <= 1; dy++){ for(int dx = -1; dx <= 1; dx++){ if(dy == 0 && dx == 0) continue; int ny = y + dy, nx = x + dx; if(ny < 0 || ny >= h || nx < 0 || nx >= w) continue; ll d2 = d + A[ny][nx]; if(d2 >= B[ny][nx]) continue; B[ny][nx] = d2; pq.emplace(d2, ny, nx); } } } ll ans = INF; for(int y = 0; y < h; y++){ ans = min(ans, B[y][w - 1]); } if(ans == INF) ans = -1; cout << ans << '\n'; }