#include #define debug(...) ((void)0) #define postprocess(...) ((void)0) using namespace std; using ll = long long; using ld = long double; int A[1010][1010]; bool colored[1010][1010]; int color[1010][1010]; int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0}; void solve([[maybe_unused]] int test) { int H, W; cin >> H >> W; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> A[i][j]; A[i][j] *= -1; } } colored[0][0] = true; colored[H - 1][W - 1] = true; color[0][0] = 1; color[H - 1][W - 1] = 0; priority_queue>> pque0, pque1; pque0.push({A[1][0], {1, 0}}); pque0.push({A[0][1], {0, 1}}); pque1.push({A[H - 2][W - 1], {H - 2, W - 1}}); pque1.push({A[H - 1][W - 2], {H - 1, W - 2}}); int round = 1; while (true) { assert(!pque0.empty()); bool done = false; int nx = 0; int ny = 0; while (!pque0.empty()) { auto f = pque0.top(); pque0.pop(); auto [x, y] = f.second; if (colored[x][y]) { continue; } nx = x; ny = y; color[nx][ny] = 2 - (round % 2); colored[nx][ny] = true; done = true; for (int k = 0; k < 4; k++) { int nx2 = nx + dx[k]; int ny2 = ny + dy[k]; if (nx2 < 0 || nx2 >= H || ny2 < 0 || ny2 >= W) { continue; } pque0.push({A[nx2][ny2], {nx2, ny2}}); } break; } assert(done); bool finished = false; for (int k = 0; k < 4; k++) { int nx2 = nx + dx[k]; int ny2 = ny + dy[k]; if (nx2 < 0 || nx2 >= H || ny2 < 0 || ny2 >= W) { continue; } if ((color[nx][ny] | color[nx2][ny2]) == 3) finished = true; } if (finished) break; round++; swap(pque0, pque1); } cout << round << endl; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t = 1; // cin >> t; for (int i = 1; i <= t; i++) { solve(i); } postprocess(); }