#include #define INF 1000000001LL #define LNF 1000000000000000001LL #define MOD 998244353LL #define MAX 1005 #define long long long #define all(x) x.begin(),x.end() using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n,m; cin >> n >> m; int pan[n][m]; for(int i = 0; i> pan[i][j]; } int dx[4] = {-1,0,0,1}; int dy[4] = {0,-1,1,0}; int vis[n][m]; memset(vis,0,sizeof vis); priority_queue>> pqA; priority_queue>> pqB; pqA.push({pan[0][0],{0,0}}); pqB.push({pan[n-1][m-1],{n-1,m-1}}); int cnt = -2; while(true) { pair x = pqA.top().second; pqA.pop(); while(vis[x.first][x.second]) { x = pqA.top().second; pqA.pop(); } vis[x.first][x.second] = 1; cnt++; for(int i = 0; i<4; i++) { int xx = x.first+dx[i]; int yy = x.second+dy[i]; if(xx < 0 || yy < 0 || xx>=n || yy >=m) continue; if(vis[xx][yy] == 2) { cout << cnt << endl; return 0; } if(vis[xx][yy]) continue; pqA.push({-pan[xx][yy],{xx,yy}}); } x = pqB.top().second; pqB.pop(); while(vis[x.first][x.second]) { x = pqB.top().second; pqB.pop(); } vis[x.first][x.second] = 2; cnt++; for(int i = 0; i<4; i++) { int xx = x.first+dx[i]; int yy = x.second+dy[i]; if(xx < 0 || yy < 0 || xx>=n || yy >=m) continue; if(vis[xx][yy] == 1) { cout << cnt << endl; return 0; } if(vis[xx][yy]) continue; pqB.push({-pan[xx][yy],{xx,yy}}); } } return 0; }