#include using namespace std; template ostream &operator<<(ostream &s, const pair &v) { s << "(" << v.first << ", " << v.second << ")"; return s; } template >> istream &operator>>(istream &s, T &&v) { for (auto &&x : v) s >> x; return s; } template >> ostream &operator<<(ostream &s, T &&v) { for (auto &&x : v) s << x << ' '; return s; } #ifdef LOCAL template void dbg(T... x) { char e{}; ((cerr << e << x, e = ' '), ...); } #define debug(x...) dbg(#x, '=', x, '\n') #else #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #define debug(...) ((void)0) #endif #define all(v) (v).begin(), (v).end() #define rall(v) (v).rbegin(), (v).rend() #define ff first #define ss second template inline constexpr T inf = numeric_limits::max() / 2; template bool chmin(T &a, T b) { return (b < a and (a = b, true)); } template bool chmax(T &a, T b) { return (a < b and (a = b, true)); } using u32 = unsigned int; using i64 = long long; using u64 = unsigned long long; using i128 = __int128; constexpr i64 mod = 998244353; void solve() { int n, m; cin >> n >> m; vector A(n, vector(m)); cin >> A; vector vis(n, vector(m, -1)); vector inque(n, vector(m, 0)); priority_queue> pq[2]{}; pq[0].push({-A[0][0], 0, 0}); pq[1].push({-A[n - 1][m - 1], n - 1, m - 1}); inque[0][0] = 1; inque[n - 1][m - 1] = 2; const vector> dir{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; auto safe = [&](int x, int y) -> bool { return 0 <= x and x < n and 0 <= y and y < m; }; int ans = 0; for (int cur = 0; ; cur ^= 1) { ans++; auto [_, x, y] = pq[cur].top(); pq[cur].pop(); vis[x][y] = cur; for (auto [dx, dy] : dir) { int nx = x + dx; int ny = y + dy; if (safe(nx, ny)) { if (vis[nx][ny] == (cur ^ 1)) { cout << ans - 2 << '\n'; return; } if (~inque[nx][ny] >> cur & 1) { inque[nx][ny] |= (1 << cur); pq[cur].push({-A[nx][ny], nx, ny}); } } } } } signed main() { cin.tie(0)->sync_with_stdio(false); cin.exceptions(cin.failbit); int t = 1; // cin >> t; while (t--) { solve(); } return 0; }