#include using namespace std; using ll = long long; #define rep(i, n) for (int i = 0; i < (int)(n); i++) const pair DIJ[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; ll h, w, a[1010][1010], c[1010][1010]; priority_queue> que[2]; void solve() { cin >> h >> w; rep(i, h) rep(j, w) { cin >> a[i][j]; a[i][j] *= -1; c[i][j] = -1; } c[0][0] = 1; c[h - 1][w - 1] = 0; que[1].emplace(a[0][1], 0, 1); que[1].emplace(a[1][0], 1, 0); que[0].emplace(a[h - 2][w - 1], h - 2, w - 1); que[0].emplace(a[h - 1][w - 2], h - 1, w - 2); ll turn = 0; for (;;) { turn += 1; ll va = 0, ci = 0, cj = 0; for (;;) { tie(va, ci, cj) = que[turn % 2].top(); que[turn % 2].pop(); if (c[ci][cj] == -1) { c[ci][cj] = turn % 2; break; } } for (const auto &[di, dj] : DIJ) { ll ni = ci + di; ll nj = cj + dj; if (ni < 0 || h <= ni || nj < 0 || w <= nj) continue; if (c[ni][nj] == -1) { que[turn % 2].emplace(a[ni][nj], ni, nj); } else if (c[ni][nj] == turn % 2) { continue; } else { cout << turn << '\n'; return; } } } } int main() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); int T = 1; for (int t = 0; t < T; t++) { solve(); } return 0; }