#include using namespace std; // using namespace __gnu_pbds; // #include // using Bint = boost::multiprecision::cpp_int; // #include // using namespace atcoder; // https://atcoder.github.io/ac-library/production/document_ja/ typedef long long int ll; typedef long double ld; constexpr ll mod = 1e9+7; constexpr ll INF = 9'223'372'036'854'775'807/10; #define rep(i,n) for (ll i = 0; i < ll(n); ++i) #define Rep(i,a,n) for (ll i = (a); i < ll(n); ++i) #define All(a) (a).begin(),(a).end() #define Pi acos(-1) using V = vector; using P = pair; vector dx = {1, 0, -1, 0, 1, 1, -1, -1}; vector dy = {0, 1, 0, -1, 1, -1, 1, -1}; templatebool chmax(T &a, const T &b) { if (abool chmin(T &a, const T &b) { if (b>; struct IoSetup { IoSetup() { cin.tie(nullptr); ios_base::sync_with_stdio(false); cout << setprecision(15) << fixed; } } iosetup; void print(vector &v) { for (string s : v) { cout << s << '\n'; } } template void print(vector &v, int w = 0) { for (int i = 0; i < (int)v.size(); i++) { cout << right << setw(w) << v[i] << " \n"[i == (int)v.size() - 1]; } } template void print(vector> &v, int w = 0) { for (int i = 0; i < (int)v.size(); i++) { print(v[i], w); } } template void print(const T& arg) { cout << arg << '\n'; } template void print(const T& arg, const Args&... args) { cout << arg << ' '; print(args...); } vector> grid_dijkstra(long long sy, long long sx, vector> grid) { long long H = grid.size(); long long W = grid[0].size(); vector> dist(H, vector(W, INF)); priority_queue>, vector>>, greater>>> pq; pq.push({grid[sy][sx], {sy, sx}}); // スタート地点 dist[sy][sx] = grid[sy][sx]; while(!pq.empty()) { pair> p = pq.top(); pq.pop(); long long y = p.second.first; long long x = p.second.second; rep (i, 8) { long long ny = y + dy[i]; long long nx = x + dx[i]; if (ny < 0 || ny >= H || nx < 0 || nx >= W) continue; // グリッドの外に出たらcontinue if (dist[ny][nx] > dist[y][x] + grid[ny][nx]) { // 距離が更新できるなら更新 dist[ny][nx] = dist[y][x] + grid[ny][nx]; pq.push(pair>(dist[ny][nx], P(ny, nx))); } } } return dist; } /* 使い方 dijkstra(grid, sy, sx); {sy, sx} から各頂点へダイクストラ sy: スタートy座標 (縦) sx: スタートx座標 (横) grid: コスト vector> dist = grid_dijkstra(sy, sx, grid); */ int main() { ll h, w; cin >> h >> w; h -= 2; vector> grid(h, vector(w)); rep(i,h) { rep(j,w) { cin >> grid[i][j]; if (grid[i][j] == -1) grid[i][j] = INF; } } ll ans = INF; rep(i,h) { auto dist = grid_dijkstra(i, 0, grid); rep(j,h) { chmin(ans, dist[j][w-1]); } } if (ans == INF) print(-1); else print(ans); }