#include using namespace std; void fast_io() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { fast_io(); 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]; } } using tiii = tuple; priority_queue, greater> pq[2]; pq[1].push({a[0][1], 0, 1}); pq[1].push({a[1][0], 1, 0}); pq[0].push({a[h - 2][w - 1], h - 2, w - 1}); pq[0].push({a[h - 1][w - 2], h - 1, w - 2}); vector> col(h, vector(w)); col[0][0] = -1; col[h - 1][w - 1] = 1; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; auto is_in = [&](int x, int y) { return 0 <= x && x < h && 0 <= y && y < w; }; int ans = 0; while (true) { ans++; int i = -1, j = -1; while (!pq[ans % 2].empty()) { auto [aa, ii, jj] = pq[ans % 2].top(); pq[ans % 2].pop(); if (col[ii][jj] == 0) { i = ii; j = jj; break; } } assert(i != -1); assert(j != -1); col[i][j] = ans % 2 == 0 ? 1 : -1; for (int d = 0; d < 4; d++) { int ni = i + dx[d], nj = j + dy[d]; if (!is_in(ni, nj)) { continue; } if (col[ni][nj] == 0) { pq[ans % 2].push({a[ni][nj], ni, nj}); } else if (col[ni][nj] != col[i][j]) { cout << ans << endl; return 0; } } } cout << ans << endl; }