#include using namespace std; using ll=long long; using pll=pair; using tll=tuple; using ld=long double; const ll INF=(1ll<<60); #define rep(i,n) for (ll i=0;i<(ll)(n);i++) #define all(v) v.begin(),v.end() template inline bool chmin(T &a,T b){ if(a>b){ a=b; return true; } return false; } template inline bool chmax(T &a,T b){ if(a> h >> w; vector> a(h,vector(w)); rep(i,h){ rep(j,w){ cin >> a[i][j]; } } vector> c(h,vector(w,-1)); vector pi={0,1,0,-1},pj={1,0,-1,0}; set st_0,st_1; rep(k,4){ ll ti=0+pi[k],tj=0+pj[k]; if(ti<0||h<=ti||tj<0||w<=tj) continue; st_0.insert({a[ti][tj],ti,tj}); } c[0][0]=0; rep(k,4){ ll ti=h-1+pi[k],tj=w-1+pj[k]; if(ti<0||h<=ti||tj<0||w<=tj) continue; st_1.insert({a[ti][tj],ti,tj}); } c[h-1][w-1]=1; ll x=0,ans=0; while(true){ ans++; ll v,si,sj; if(x==0){ tie(v,si,sj)=*begin(st_0); c[si][sj]=0; } if(x==1){ tie(v,si,sj)=*begin(st_1); c[si][sj]=1; } st_0.erase({v,si,sj}); st_1.erase({v,si,sj}); rep(k,4){ ll ti=si+pi[k],tj=sj+pj[k]; if(ti<0||h<=ti||tj<0||w<=tj) continue; if(c[ti][tj]!=-1&&c[si][sj]==1-c[ti][tj]){ cout << ans << '\n'; return 0; } if(c[ti][tj]!=-1) continue; if(x==0) st_0.insert({a[ti][tj],ti,tj}); if(x==1) st_1.insert({a[ti][tj],ti,tj}); } x++; x%=2; } }