#include using namespace std; using uint = unsigned int; using ll = long long; using ull = unsigned long long; template using V = vector; template using VV = V>; template using VVV = V>; template using VVVV = VV>; #define rep(i,n) for(ll i=0ll;i void chmin(T& t, const U& u) { if (t > u) t = u; } template void chmax(T& t, const U& u) { if (t < u) t = u; } // cin.tie(nullptr); // ios::sync_with_stdio(false); // cout << fixed << setprecision(20); void solve(){ ll h,w; cin >> h >> w; VV v(h, V(w)); rep(i, h) rep(j, w) cin >> v[i][j]; VV c(h, V(w, -1)); V>> st(2); c[0][0] = 1; c[h-1][w-1] = 0; st[0].insert({v[h-2][w-1], h-2, w-1}); st[0].insert({v[h-1][w-2], h-1, w-2}); st[1].insert({v[0][1], 0, 1}); st[1].insert({v[1][0], 1, 0}); V dx = {0, 1, 0, -1}, dy = {1, 0, -1, 0}; ll ans = 0; while(1){ ans++; ll id = ans%2; auto[a,x,y] = *(st[ans%2].begin()); st[ans%2].erase(st[id].begin()); while(c[x][y]!=-1){ auto[aa,xx,yy] = *(st[id%2].begin()); st[id%2].erase(st[id].begin()); x = xx; y = yy; } // cout << x << " " << y << endl; c[x][y] = id; ll f = 1; rep(i, 4){ ll nx = x+dx[i]; ll ny = y+dy[i]; if(nx<0||h<=nx) continue; if(ny<0||w<=ny) continue; if(c[nx][ny]==id) continue; if(c[nx][ny]==1-id){ f = 0; continue; } st[id].insert({v[nx][ny], nx, ny}); } if(f==0) break; } cout << ans << endl; } int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); int t=1; // cin >> t; rep(i,t) solve(); }