#include using namespace std; using ll = long long; const int INF = 1e9 + 10; const ll INFL = 4e18; const vector dx = {0, 1, 0, -1}; const vector dy = {1, 0, -1, 0}; int main() { int H, W; cin >> H >> W; vector> A(H, vector(W)); for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { cin >> A[i][j]; } } vector, vector>, greater>>> pq(2); pq[0].push({A[0][0], 0, 0}); pq[1].push({A[H - 1][W - 1], H - 1, W - 1}); vector>> vst(2, vector>(H, vector(W, false))); int ans = 0; bool fin = false; int i = 0; while (true) { auto [a, x, y] = pq[i % 2].top(); pq[i % 2].pop(); if (vst[i % 2][x][y]) { continue; } vst[i % 2][x][y] = true; for (int j = 0; j < 4; j++) { int nx = x + dx[j]; int ny = y + dy[j]; if (nx < 0 || nx >= H || ny < 0 || ny >= W) { continue; } if (vst[i % 2][nx][ny]) { continue; } if (vst[(i + 1) % 2][nx][ny]) { ans = i - 1; fin = true; break; } pq[i % 2].push({A[nx][ny], nx, ny}); } if (fin) { break; } i++; } cout << ans << endl; }