#include #include using namespace std; using namespace atcoder; typedef long long int ll; typedef pair P; typedef vector VI; typedef vector VVI; #define REP(i,n) for(int i=0;i<(n);i++) #define ALL(v) v.begin(),v.end() template bool chmax(T& x, const T& y){return (x bool chmin(T& x, const T& y){return (x>y)?(x=y,true):false;}; constexpr ll MOD=998244353; constexpr ll INF=2e18; const int dx[8]={1,0,-1,0,1,1,-1,-1}, dy[8]={0,1,0,-1,1,-1,1,-1}; int main(){ int h, w; cin >> h >> w; h-=2; VVI a(h,VI(w)); REP(i,h)REP(j,w) cin >> a[i][j]; mcf_graph g(h*w+2); int s=h*w, t=h*w+1; REP(i,h)REP(j,w){ if(a[i][j]==-1) continue; REP(k,8){ int ti=i+dx[k], tj=j+dy[k]; if(ti<0||ti>=h||tj<0||tj>=w) continue; g.add_edge(i*w+j,ti*w+tj,1,a[i][j]); if(j==0) g.add_edge(s,i*w+j,1,0); else if(j==w-1) g.add_edge(i*w+j,t,1,a[i][j]); } } auto ans=g.flow(s,t,1); if(ans.first==0) cout << -1 << endl; else cout << ans.second << endl; return 0; }