#define rep(i,n) for(int i=0;i<(int)(n);i++) #define ALL(v) v.begin(),v.end() typedef long long ll; #include using namespace std; const int INF=1e9; struct Edge{ int to; int w; Edge(int to,ll w) : to(to),w(w) {} }; using Graph=vector>; using pli=pair; template bool chmin(T& a,T b){ if(a>b){ a=b; return true; } return false; } Graph G; vector dijkstra(int s){ int n=G.size(); vector dist(n,INF); dist[s]=0; priority_queue,greater> que; que.push({dist[s],s}); while(!que.empty()){ int v=que.top().second; int d=que.top().first; que.pop(); if(d>dist[v]) continue; for(auto e:G[v]){ if(chmin(dist[e.to],dist[v]+e.w)){ que.push({dist[e.to],e.to}); } } } return dist; } int main(){ ios::sync_with_stdio(false); std::cin.tie(nullptr); int h,w; cin>>h>>w; auto f=[&](int x,int y){ return x*w+y; }; G.resize((h-2)*w+2); int s=(h-2)*w,t=s+1; vector> A(h-2,vector(w)); rep(i,h-2) rep(j,w) cin>>A[i][j]; rep(i,h-2){ if(A[i][0]!=0) G[s].push_back(Edge(f(i,0),A[i][0])); } rep(i,h-2){ if(A[i][w-1]!=0) G[f(i,w-1)].push_back(Edge(t,0)); } rep(i,h-2) rep(j,w){ if(A[i][j]==-1) continue; if(i dis=dijkstra(s); if(dis[t]==INF) cout<<-1<