#include #define chmin(x,y) (x) = min((x),(y)) using namespace std; using ll = long long; bool debug = 0; const vector dx = {1,1,0,-1,-1,-1,0,1}, dy = {0,1,1,1,0,-1,-1,-1}; int main(){ // input int H,W; cin >> H >> W; vector> A(H,vector(W,-1)); for (int i = 1; i + 1 < H; i++) for (int j = 0; j < W; j++) cin >> A[i][j]; // solve: dijkstra vector> dis(H,vector(W,9e18)); priority_queue> pq; // {cost,cur_x,cur_y} for (int i = 1; i + 1 < H; i++){ if(A[i][0] != -1){ pq.push({-A[i][0],i,0}); dis[i][0] = A[i][0]; } } while(!pq.empty()){ ll cost = -pq.top()[0], cur_x = pq.top()[1], cur_y = pq.top()[2]; pq.pop(); // chmin(dis[cur_x][cur_y],cost); for(int j = 0; j < 8; j++){ ll nxt_x = cur_x + dx[j], nxt_y = cur_y + dy[j]; if(nxt_x < 0 || nxt_x >= H || nxt_y < 0 || nxt_y >= W) continue; if(A[nxt_x][nxt_y] == -1) continue; if(dis[nxt_x][nxt_y] > cost + A[nxt_x][nxt_y]){ dis[nxt_x][nxt_y] = cost + A[nxt_x][nxt_y]; pq.push({-(cost+A[nxt_x][nxt_y]),nxt_x,nxt_y}); if(debug) cout << nxt_x << " " << nxt_y << " " << cost + A[nxt_x][nxt_y] << endl; } } } // output ll ans = 9e18; for (int i = 0; i < H; i++){ if(debug) cout << i << ":" << dis[i][W-1] << endl; chmin(ans,dis[i][W-1]); } cout << (ans < 2e9? ans : -1) << endl; }