#include #define chmin(x,y) (x) = min((x),(y)) #define chmax(x,y) (x) = max((x),(y)) using namespace std; using ll = long long; int main(){ // input int H,W; cin >> H >> W; H-= 2; vector> A(H,vector(W)); for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) cin >> A[i][j]; // solve: dp vector> dp(W+1,vector(H,9e18)); for (int j = 0; j < H; j++) dp[0][j] = 0; for (int i = 0; i < W; i++){ for (int j = 0; j < H; j++){ ll cost = A[j][i]; if(cost == -1) continue; chmin(dp[i+1][j],dp[i][j]+cost); if(j > 0) chmin(dp[i+1][j],dp[i][j-1]+cost); if(j + 1 < H) chmin(dp[i+1][j],dp[i][j+1]+cost); // cout << i << " " << j << " " << dp[i+1][j] << endl; } } // output ll ans = 9e18; for (int j = 0; j < H; j++) chmin(ans,dp[W][j]); cout << (ans < 9e18? ans : -1) << endl; }