#pragma GCC optimize("Ofast") #include using namespace std; typedef long long int ll; typedef unsigned long long int ull; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); ll myRand(ll B) { return (ull)rng() % B; } inline double time() { return static_cast(chrono::duration_cast(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9; } template struct Dijkstra{ const T inf=numeric_limits::max(); using P=pair; int n; vector>> g; vector d; Dijkstra(int n):n(n),g(n),d(n){} void add_edge(int u,int v,T w){ g[u].emplace_back(v,w); } vector build(int s){ for(int i=0;i,greater

> pq; pq.emplace(d[s],s); while(pq.size()){ P p=pq.top(); pq.pop(); int v=p.second; if(d[v]d[v]+c){ d[u]=d[v]+c; pq.emplace(d[u],u); } } } return d; } }; int dx[] = {1,-1,0,0,1,1,-1,-1}; int dy[] = {0,0,1,-1,1,-1,1,-1}; int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); int h,w; cin >> h >> w; vector> a(h-2,vector(w)); for (int i = 0; i < h - 2; ++i) { for (int j = 0; j < w; ++j) { cin >> a[i][j]; } } h -= 2; Dijkstra g(h*w+2); int S = h*w, T = h*w+1; for (int i = 0; i < h; ++i) { if (a[i][0] != -1) g.add_edge(S, i*w+0, a[i][0]); if (a[i][w-1] != -1) g.add_edge(i*w+w-1, T, 0); } for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { if (a[i][j] == -1) continue; for (int k = 0; k < 8; ++k) { int nx = i+dx[k], ny = j+dy[k]; if (0 <= nx and nx < h and 0 <= ny and ny < w and a[nx][ny] != -1) { g.add_edge(i*w+j, nx*w+ny, a[nx][ny]); } } } } ll res = g.build(S)[T]; if (res == numeric_limits::max()) res = -1; cout << res << endl; }