#define _USE_MATH_DEFINES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; int H, W; int A[1010][1010]; int dx[4] = {1,0,-1,0}; int dy[4] = {0,1,0,-1}; int main() { cin >> H >> W; for(int i = 0; i < H; ++i) { for(int j = 0; j < W; ++j) cin >> A[i][j]; } vector vis(H, vector(W, -1)); // priority_queue>, // vector>>, // greater>>> pq1,pq0; set>> st1,st0; st1.insert({A[0][0], {0,0}}); st0.insert({A[H-1][W-1], {H-1,W-1}}); int cnt = -2; while(1) { cnt++; auto [v1, p1] = *st1.begin(); auto [y1, x1] = p1; st1.erase(st1.begin()); vis[y1][x1] = 1; bool f = false; for(int i = 0; i < 4; ++i) { int nx = x1+dx[i]; int ny = y1+dy[i]; if(nx < 0 || nx >= W || ny < 0 || ny >= H) continue; if(vis[ny][nx] == 0) { f = true; break; } if(vis[ny][nx] == -1) { st1.insert({A[ny][nx], {ny,nx}}); } } if(f) break; cnt++; auto [v0, p0] = *st0.begin(); auto [y0, x0] = p0; st0.erase(st0.begin()); vis[y0][x0] = 0; for(int i = 0; i < 4; ++i) { int nx = x0+dx[i]; int ny = y0+dy[i]; if(nx < 0 || nx >= W || ny < 0 || ny >= H) continue; if(vis[ny][nx] == 1) { f = true; break; } if(vis[ny][nx] == -1) { st0.insert({A[ny][nx], {ny,nx}}); } } if(f) break; } cout << cnt << endl; // for(int i = 0; i < H; ++i) { // for(int j = 0; j < W; ++j) cout << vis[i][j] << " "; // cout << endl; // } }