#include using namespace std; struct iofast_t { iofast_t() { ios::sync_with_stdio(false); cin.tie(nullptr); } } iofast; struct uns_t {} uns; template auto vec(Element init, Head arg, Args ...args) { if constexpr (sizeof...(Args) == 0) return vector(arg, init); else return vector(arg, vec(init, args...)); } template auto vec(uns_t, Head arg, Args ...args) { return vec(Element(), arg, args...); } template auto distance(const Container &c, decltype(begin(c)) iter) { return distance(begin(c), iter); } template ::value_type>> auto isort(RIter first, RIter last, Compare comp = Compare()) { vector i(distance(first, last)); iota(begin(i), end(i), 0); sort(begin(i), end(i), [&](auto x, auto y) { return comp(*(first + x), *(first + y)); }); return i; } template typename, typename = void_t<>> struct detect : false_type {}; template typename Check> struct detect>> : true_type {}; template typename Check> constexpr inline bool detect_v = detect::value; template using has_member_sort = decltype(declval().sort()); template > auto sorted(Container c, Compare comp = Compare()) { if constexpr (detect_v) { c.sort(comp); return c; } else { sort(begin(c), end(c), comp); return c; } } template > auto uniqued(Container c, Compare comp = Compare()) { c.erase(unique(begin(c), end(c), comp), end(c)); return c; } template > T &chmin(T &l, T r, Compare &&f = less()) { return l = min(l, r, f); } template > T &chmax(T &l, T r, Compare &&f = less()) { return l = max(l, r, f); } template constexpr auto fix(F &&f) noexcept { return [f = std::tuple(std::forward(f))](auto &&...args) mutable { return std::get<0>(f)(fix(std::get<0>(f)), std::forward(args)...); }; } template using pqueue = priority_queue, greater>; int main() { constexpr auto inf = INT_MAX / 2; constexpr int step[5][2] = { { -1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 }, { 1, 0 }, }; int h, w; cin >> h >> w; auto a = vec(-1, h, w); for (int i = 1; i < h - 1; ++i) { for (int j = 0; j < w; ++j) { cin >> a[i][j]; } } auto dist = vec(inf, h, w); pqueue> que; for (int i = 0; i < h; ++i) { if (a[i][0] < 0) { continue; } que.push({ a[i][0], i, 0 }); dist[i][0] = a[i][0]; } while (!empty(que)) { auto [d, y, x] = que.top(); que.pop(); if (dist[y][x] < d) { continue; } for (auto [dy, dx] : step) { int ny = y + dy; int nx = x + dx; if (min(ny, nx) < 0 || h <= ny || w <= nx) { continue; } if (a[ny][nx] < 0) { continue; } if (dist[ny][nx] <= d + a[ny][nx]) { continue; } dist[ny][nx] = d + a[ny][nx]; que.push({ dist[ny][nx], ny, nx }); } } int ans = inf; for (int i = 0; i < h; ++i) { chmin(ans, dist[i][w - 1]); } if (ans != inf) { cout << ans << endl; } else { cout << -1 << endl; } }