#include using namespace std; vector di = {-1, 0, 1, 0}; vector dj = {0, 1, 0, -1}; 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]; } } auto inc = [&](int i, int j) { return (0 <= i && i < h && 0 <= j && j < w); }; vector> b(h, vector(w, -1)); vector> visit(h, vector(w, false)); b[0][0] = 1; visit[0][0] = true; b[h - 1][w - 1] = 0; visit[h - 1][w - 1] = true; vector, vector>, greater>>> pq(2); pq[1].push({a[0][1], 0, 1}); visit[0][1] = true; pq[1].push({a[1][0], 1, 0}); visit[1][0] = true; pq[0].push({a[h - 1][w - 2], h - 1, w - 2}); visit[h - 1][w - 2] = true; pq[0].push({a[h - 2][w - 1], h - 2, w - 1}); visit[h - 2][w - 1] = true; int cnt = 0; while (true) { cnt++; int id = cnt % 2; auto [x, i, j] = pq[id].top(); pq[id].pop(); b[i][j] = id; bool ok = true; for (int k = 0; k < 4; k++) { int ni = i + di[k], nj = j + dj[k]; if (!inc(ni, nj)) { continue; } if (b[ni][nj] == 1 - id) { ok = false; } else if (b[ni][nj] == -1 && !visit[ni][nj]) { visit[ni][nj] = true; pq[id].push({a[ni][nj], ni, nj}); } } if (!ok) { break; } } cout << cnt << endl; }