#include #include #include using namespace std; constexpr int iINF = 1'000'000'000; 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]; } // グリッド上のダイクストラ法に帰着 priority_queue>, vector>>, greater>>> pq1, pq2; vector> vis1(H, vector(W, false)), vis2(H, vector(W, false)); pq1.push(make_pair(A[0][0], make_pair(0, 0))); pq2.push(make_pair(A[H - 1][W - 1], make_pair(H - 1, W - 1))); const vector> dxy = { make_pair(0, 1), make_pair(0, -1), make_pair(1, 0), make_pair(-1, 0), }; bool end = false; int ans = 0; while (true) { { int y, x, c; while (true) { auto h = pq1.top(); pq1.pop(); c = h.first; y = h.second.first, x = h.second.second; if (vis1[y][x]) continue; break; } vis1[y][x] = true; ans++; for (auto d : dxy) { int ny = y + d.first, nx = x + d.second; if (!(0 <= ny && ny < H && 0 <= nx && nx < W)) continue; if (vis1[ny][nx]) continue; // 相手側がもう塗られている if (vis2[ny][nx]) { end = true; break; } pq1.push(make_pair(A[ny][nx], make_pair(ny, nx))); } } if (end) break; { int y, x, c; while (true) { auto h = pq2.top(); pq2.pop(); c = h.first; y = h.second.first, x = h.second.second; if (vis2[y][x]) continue; break; } vis2[y][x] = true; ans++; for (auto d : dxy) { int ny = y + d.first, nx = x + d.second; if (!(0 <= ny && ny < H && 0 <= nx && nx < W)) continue; if (vis2[ny][nx]) continue; // 相手側がもう塗られている if (vis1[ny][nx]) { end = true; break; } pq2.push(make_pair(A[ny][nx], make_pair(ny, nx))); } } if (end) break; } cout << ans - 2 << "\n"; }