#include using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() using ll = long long; constexpr int INF = 0x3f3f3f3f; constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL; constexpr double EPS = 1e-8; constexpr int MOD = 998244353; // constexpr int MOD = 1000000007; constexpr int DY4[]{1, 0, -1, 0}, DX4[]{0, -1, 0, 1}; constexpr int DY8[]{1, 1, 0, -1, -1, -1, 0, 1}; constexpr int DX8[]{0, -1, -1, -1, 0, 1, 1, 1}; template inline bool chmax(T& a, U b) { return a < b ? (a = b, true) : false; } template inline bool chmin(T& a, U b) { return a > b ? (a = b, true) : false; } struct IOSetup { IOSetup() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); std::cout << fixed << setprecision(20); } } iosetup; template struct Edge { CostType cost; int src, dst; explicit Edge(const int src, const int dst, const CostType cost = 0) : cost(cost), src(src), dst(dst) {} auto operator<=>(const Edge& x) const = default; }; template struct Dijkstra { const CostType inf; Dijkstra(const std::vector>>& graph, const CostType inf = std::numeric_limits::max()) : inf(inf), is_built(false), graph(graph) {} std::vector build(const int s) { is_built = true; const int n = graph.size(); std::vector dist(n, inf); dist[s] = 0; prev.assign(n, -1); std::priority_queue, std::vector>, std::greater>> que; que.emplace(0, s); while (!que.empty()) { const auto [d, ver] = que.top(); que.pop(); if (d > dist[ver]) continue; for (const Edge& e : graph[ver]) { if (dist[ver] + e.cost < dist[e.dst]) { dist[e.dst] = dist[ver] + e.cost; prev[e.dst] = ver; que.emplace(dist[e.dst], e.dst); } } } return dist; } std::vector build_path(int t) const { assert(is_built); std::vector res; for (; t != -1; t = prev[t]) { res.emplace_back(t); } std::reverse(res.begin(), res.end()); return res; } private: bool is_built; std::vector prev; std::vector>> graph; }; int main() { int h, w; cin >> h >> w; vector a(h - 2, vector(w, 0)); REP(i, h - 2) REP(j, w) cin >> a[i][j]; vector>> graph((h - 2) * w + 2); const auto id = [&](const int y, const int x) -> int { return y * w + x; }; REP(i, h - 2) { if (a[i][0] != -1) graph[(h - 2) * w].emplace_back((h - 2) * w, id(i, 0), a[i][0]); } REP(i, h - 2) REP(j, w) { if (a[i][j] == -1) continue; REP(k, 8) { const int y = i + DY8[k], x = j + DX8[k]; if (0 <= y && y < h - 2 && 0 <= x && x < w && a[y][x] != -1) { graph[id(i, j)].emplace_back(id(i, j), id(y, x), a[y][x]); } } } REP(i, h - 2) { if (a[i][w - 1] != -1) graph[id(i, w - 1)].emplace_back(id(i, w - 1), (h - 2) * w + 1, 0); } const ll ans = Dijkstra(graph, LINF).build((h - 2) * w)[(h - 2) * w + 1]; cout << (ans == LINF ? -1 : ans) << '\n'; return 0; }