#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; int dx[]={0,-1,-1,-1,0,1,1,1}; int dy[]={1,1,0,-1,-1,-1,0,1}; int main(){ ios::sync_with_stdio(false); std::cin.tie(nullptr); int h,w; cin>>h>>w; vector> A(h-2,vector(w)); rep(i,h-2) rep(j,w) cin>>A[i][j]; int ans=INF; rep(i,h-2){ if(A[i][0]==-1) continue; queue> que; vector> dist(h-2,vector(w,INF)); dist[i][0]=A[i][0]; que.push({i,0}); rep(j,8){ int nx=i+dx[j],ny=0+dy[j]; if(nx<0 || ny<0 || nx>=h-2 || ny>=w) continue; if(A[nx][ny]==-1) continue; dist[nx][ny]=dist[i][0]+A[nx][ny]; que.push({nx,ny}); } while(que.size()){ auto p=que.front(); que.pop(); int x=p.first,y=p.second; rep(j,8){ int nx=x+dx[j],ny=y+dy[j]; if(nx<0 || ny<0 || nx>=h-2 || ny>=w) continue; if(A[nx][ny]==-1) continue; if(dist[nx][ny]>dist[x][y]+A[nx][ny]){ dist[nx][ny]=dist[x][y]+A[nx][ny]; que.push({nx,ny}); } } } rep(i,h-2) ans=min(ans,dist[i][w-1]); } if(ans==INF) cout<<-1<