#include namespace { #pragma GCC diagnostic ignored "-Wunused-function" #include #pragma GCC diagnostic warning "-Wunused-function" using namespace std; using namespace atcoder; #define rep(i,n) for(int i = 0; i < (int)(n); i++) #define rrep(i,n) for(int i = (int)(n) - 1; i >= 0; i--) #define all(x) begin(x), end(x) #define rall(x) rbegin(x), rend(x) template bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } else return false; } template bool chmin(T& a, const T& b) { if (b < a) { a = b; return true; } else return false; } using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; const unsigned long long INF = 1002003004005006007; template std::vector dijkstra(std::vector>>& to, int s=0) { struct QueElem { int v; unsigned long long c; bool operator<(const QueElem a) const {return c > a.c;} QueElem(int v, unsigned long long c): v(v), c(c) {} }; std::priority_queue q; std::vector dist(to.size(), INF); dist[s] = 0; q.emplace(s, 0); while(!q.empty()) { QueElem qe = q.top(); q.pop(); int u = qe.v; unsigned long long c = qe.c; if (c > dist[u]) continue; for(auto vc: to[u]) { int v = vc.first; unsigned long long nc = c + vc.second; if (nc < dist[v]) { dist[v] = nc; q.emplace(v, nc); } } } return dist; } } int main() { ios::sync_with_stdio(false); cin.tie(0); int h, w; cin >> h >> w; VVI a(h, VI(w, -1)); rep(i, h) if (1 <= i && i < h - 1) rep(j, w) cin >> a[i][j]; int s = h * w, t = s + 1; vector> to(t + 1); rep(i, h) if (a[i][0] != -1) { int v = i * w; to[s].emplace_back(v, a[i][0]); } rep(i, h) if (a[i][w - 1] != -1) { int v = i * w + w - 1; to[v].emplace_back(t, 0); } rep(i, h) rep(j, w) if (a[i][j] != -1) { int u = i * w + j; for(int di = -1; di <= 1; di++) { for(int dj = -1; dj <= 1; dj++) { if (di == 0 && dj == 0) continue; int ni = i + di, nj = j + dj; if (!(0 <= ni && ni < h && 0 <= nj && nj < w) || a[ni][nj] == -1) continue; int v = ni * w + nj; to[u].emplace_back(v, a[ni][nj]); } } } ll ans = dijkstra(to, s)[t]; if (ans == INF) ans = -1; cout << ans << '\n'; }