#include #include using namespace std; using namespace atcoder; #define rep(i, n) for(int i=0;i<(n);++i) #define rep1(i, n) for(int i=1;i<=(n);i++) #define ll long long using mint = modint998244353; using P = pair; using lb = long double; using T = tuple; #ifdef LOCAL # include # define dbg(...) debug_print::multi_print(#__VA_ARGS__, __VA_ARGS__) #else # define dbg(...) (static_cast(0)) #endif int main() { int h, w; cin >> h >> w; vector> a(h, vector(w)); rep(i,h)rep(j,w) cin >> a[i][j]; vector> used(h, vector(w, -1)); priority_queue, greater> pq1, pq0; vector di = {0, 1, 0, -1}; vector dj = {1, 0, -1, 0}; auto add = [&](int x, int y, int t) { rep(d,4) { int ni = x + di[d]; int nj = y + dj[d]; if(ni<0 || ni>=h || nj<0 || nj>=w) continue; if(used[ni][nj]!=-1) continue; if(t==0) pq0.emplace(a[ni][nj], ni, nj); else pq1.emplace(a[ni][nj], ni, nj); } }; add(0, 0, 1); add(h-1, w-1, 0); used[0][0] = 1; used[h-1][w-1] = 0; int ans = 0; while(!pq0.empty() && !pq1.empty()) { if(ans%2==0) { while(!pq1.empty()) { auto [val, x,y] = pq1.top();pq1.pop(); if(used[x][y]!=-1) continue; used[x][y] = 1; add(x, y, 1); ans++; dbg(x,y,val); rep(d,4) { int ni = x + di[d]; int nj = y + dj[d]; if(ni<0 || ni>=h || nj<0 || nj>=w) continue; if(used[ni][nj]==0) { cout << ans << endl; exit(0); } } break; } } else{ while(!pq0.empty()) { auto [val, x,y] = pq0.top();pq0.pop(); if(used[x][y]!=-1) continue; used[x][y] = 0; add(x, y, 0); ans++; dbg(x,y,val); rep(d,4) { int ni = x + di[d]; int nj = y + dj[d]; if(ni<0 || ni>=h || nj<0 || nj>=w) continue; if(used[ni][nj]==1) { cout << ans << endl; exit(0); } } break; } } } cout << ans << endl; return 0; }