#include #include using namespace std; using namespace atcoder; // type typedef long long ll; typedef long double ld; using i128 = __int128_t; template using pq = priority_queue; template using pqg = priority_queue, greater>; template using v = vector; #define V vector #define pl pair #define vl v #define vp v #define vm v // IN-OUT #define NYAN ios::sync_with_stdio(false);cin.tie(nullptr);cout< 0; num /= 10) { s.push_back((char)(num % 10) + '0'); } reverse(s.begin(), s.end()); return (os << s); } void Yes(bool b=1) { cout << ( b == 1 ? "Yes" : "No" ) << "\n"; } void YES(bool b=1) { cout << ( b == 1 ? "YES" : "NO" ) << "\n"; } void No(bool b=1) { cout << ( b == 1 ? "No" : "Yes" ) << "\n"; } void NO(bool b=1) { cout << ( b == 1 ? "NO" : "YES" ) << "\n"; } void CIN() {} template void CIN(T &t, U &...u) { cin >> t; CIN(u...); } void COUT() { cout << "\n"; } template void COUT(const T &t, const U &...u) { cout << t; if (sizeof...(u)) cout << sep; COUT(u...); } #define dump(x) cerr << #x << ":"<< x << "\n"; #define vdump(x) rep(repeat, sz(x)) cerr << repeat << ":" << x[repeat] << "\n"; // macro #define bp __builtin_popcountll #define ALL(x) x.begin(),x.end() #define rep(i, n) for (ll i = 0; i < (ll)(n); i++) #define reps(i, s, n) for (ll i = s; i < (ll)(n); i++) #define sz(x) (ll)x.size() ll xd[]={0, 1, 0, -1, 1, 1, -1, -1}; ll yd[]={1, 0, -1, 0, 1, -1, -1, 1}; // function templatebool chmax(T &a, const T &b) { if (abool chmin(T &a, const T &b) { if (bint bl(T x) { int s = 0; while(x) {x >>= 1; s++;} return s; } // bitlength ll rmax(ll a, ll b){return max(a, b);} ll rmin(ll a, ll b){return min(a, b);} ll rsum(ll a, ll b){return a + b;} ll rzero(){return 0;} // constant long double PI = 3.14159265358979; #define INF32 2147483647 #define INF64 9223372036854775807 #define INF 922337203685477580 using mint = modint998244353; // using mint = modint1000000007; /* SOLVE BEGIN ************************************************************************** */ void solve() { ll h, w; cin >> h >> w; v g(h, vl(w)); rep(i, h)rep(j, w) cin >> g[i][j]; v used(h, vl(w, -1)); used[0][0] = 1; used[h - 1][w - 1] = 0; v>> s(2); auto ng = [&](ll x, ll y){ return x < 0 || y < 0 || x >= h || y >= w; }; rep(i, 4){ ll x = xd[i], y = yd[i]; if(ng(x, y)) continue; s[1].emplace(g[x][y], x, y); } rep(i, 4){ ll x = xd[i] + h - 1, y = yd[i] + w - 1; if(ng(x, y)) continue; s[0].emplace(g[x][y], x, y); } ll ans = 0; reps(i, 1, INF){ ll mod = i % 2; if(sz(s[mod]) == 0) break; ans++; auto it = s[mod].begin(); auto [num, x, y] = *it; s[mod].erase(*it); used[x][y] = mod; rep(k, 4){ ll nx = x + xd[k], ny = y + yd[k]; if(ng(nx, ny)) continue; if(used[nx][ny] == (mod ^ 1)){ cout << ans << "\n"; return; } if(used[nx][ny] == -1) s[mod].emplace(g[nx][ny], nx, ny); } } cout << ans << "\n"; } int main() { NYAN solve(); return 0; }