#include #include #include using namespace std; using namespace atcoder; #define print(n) cout << (n) << endl #define fprint(n) cout << setprecision(16) << (n) << endl #define ceil_div(a, b) (((a) - 1) / (b) + 1) #define rep(i, l, n) for (int i = (l); i < (n); i++) #define itrep(itr, st) for (auto itr = st.begin(); itr != st.end(); itr++) #define ite(i, a) for (auto& i : a) #define all(x) x.begin(), x.end() #define lb(A, x) (lower_bound(all(A), x) - A.begin()) #define ub(A, x) (upper_bound(all(A), x) - A.begin()) using str = string; using ll = long long; using u32 = unsigned int; using u64 = unsigned long long; using Pair = pair; using mint = modint1000000007; using Mint = modint998244353; template using V = vector; template using VV = V >; template using PQ = priority_queue, greater >; template using PQR = priority_queue; template using BIT = fenwick_tree; const ll INF = 4611686018427387903; const int inf = 2147483647; const ll mod = 1000000007; const ll MOD = 998244353; template inline V getList(int n) { V res(n); rep(i, 0, n) { cin >> res[i]; }return res; } template inline VV getGrid(int m, int n) { VV res(m, V(n)); rep(i, 0, m) { res[i] = getList(n); }return res; } template inline void prints(V& vec) { if (vec.size() == 0)return; cout << vec[0]; rep(i, 1, vec.size()) { cout << ' ' << vec[i]; } cout << '\n'; } inline V dtois(string& s) { V vec = {}; ite(e, s) { vec.push_back(e - '0'); } return vec; } inline V atois(string& s) { V vec = {}; ite(e, s) { vec.push_back(e - 'a'); } return vec; } inline V Atois(string& s) { V vec = {}; ite(e, s) { vec.push_back(e - 'A'); } return vec; } int main(void) { int n, m; cin >> n >> m; VV a = getGrid(n, m); VV > dp(n, V >(m, { INF,INF })); dp[0][0].first = 0; PQ > que = {}; que.push({ 0ll ,0ll,0ll,0ll }); while (que.empty() == false) { V vec = que.top(); que.pop(); ll c = vec[0], p = vec[1], q = vec[2], r = vec[3]; if ((r == 0 and c > dp[p][q].first) or (r == 1 and c > dp[p][q].second)) { continue; } if (p == n - 1) { print(c); break; } if (q > 0 and c < dp[p][q - 1].first) { dp[p][q - 1].first = c; que.push({ c, p, q - 1, 0 }); } if (q < m - 1 and c < dp[p][q + 1].first) { dp[p][q + 1].first = c; que.push({ c, p, q + 1, 0 }); } if (r == 0) { ll nc = c + a[p][q]; if (nc >= dp[p][q].second) { continue; } dp[p][q].second = nc; que.push({ nc,p,q,1 }); } else { ll nc = c + a[p + 1][q]; if (nc >= dp[p + 1][q].second) { continue; } dp[p + 1][q].second = nc; que.push({ nc,p + 1,q,1 }); } } return 0; }