#include #define chmin(x,y) (x) = min((x),(y)) using namespace std; using ll = long long; int main(){ // input int H,W; cin >> H >> W; H -= 2; vector> A(W,vector(H)); for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) cin >> A[j][i]; // 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[i][j]; if(cost == -1) continue; chmin(dp[i+1][j],dp[i][j]+cost); ll cos_u = cost; for (int k = j - 1; k >= 0; k--){ chmin(dp[i+1][j],dp[i][k]+cos_u); if(A[i][k] > 0) cos_u += A[i][k]; else break; } ll cos_d = cost; for (int k = j + 1; k < H; k++){ chmin(dp[i+1][j],dp[i][k]+cos_d); if(A[i][k] > 0) cos_d += A[i][k]; else break; } } } // output ll ans = 9e18; for (int j = 0; j < H; j++) ans = min(ans,dp[W][j]); cout << (ans < 9e18? ans : -1) << endl; }