#include using namespace std; const int INF = 1 << 30; vector dx = {-1, -1, -1, 0, 0, 1, 1, 1}; vector dy = {-1, 0, 1, -1, 1, -1, 0, 1}; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int h, w; cin >> h >> w; vector> a(h, vector(w)); for(int i = 1; i < h - 1; i++){ for(int j = 0; j < w; j++){ cin >> a[i][j]; } } vector> res(h, vector(w, INF)); using T = tuple; priority_queue, greater> q; for(int i = 1; i < h - 1; i++){ if(a[i][0] != -1){ q.emplace(a[i][0], i, 0); res[i][0] = a[i][0]; } } while(q.size()){ auto [cost, x, y] = q.top(); q.pop(); if(cost > res[x][y]){ continue; } for(int i = 0; i < 8; i++){ int x2 = x + dx[i], y2 = y + dy[i]; if(1 <= x2 && x2 < h - 1 && 0 <= y2 && y2 < w){ if(a[x2][y2] == -1) continue; if(res[x2][y2] > cost + a[x2][y2]){ res[x2][y2] = cost + a[x2][y2]; q.emplace(res[x2][y2], x2, y2); } } } } int ans = INF; for(int i = 1; i < h - 1; i++){ ans = min(ans, res[i][w - 1]); } if(ans == INF){ cout << -1 << endl; }else{ cout << ans << endl; } }