#include #include #define chmin(x,y) (x) = min((x),(y)) #define chmax(x,y) (x) = max((x),(y)) #define ld long double using namespace std; using namespace atcoder; using ll = long long; const ll mod = 998244353; using mint = modint998244353; using Graph = vector>>; const vector dx = {1,0,-1,0}, dy = {0,1,0,-1}; int main(){ // input int H,W; cin >> H >> W; vector> A(H+2,vector(W+2,2e9)); for(int i = 1; i <= H; i++) for(int j = 1; j <= W; j++) cin >> A[i][j]; // solve int ans = 0; vector> color(H+2,vector(W+2,-1)); set> ad_r, ad_b; priority_queue> nxt_r, nxt_b; color[1][1] = 1, color[H][W] = 0; ad_r.insert({1,2}); ad_r.insert({2,1}); ad_b.insert({H-1,W}); ad_b.insert({H,W-1}); nxt_r.push({-A[1][2],1,2}); nxt_r.push({-A[2][1],2,1}); nxt_b.push({-A[H-1][W],H-1,W}); nxt_b.push({-A[H][W-1],H,W-1}); bool adj = 0; while(!adj){ ans++; if(ans % 2){ int nxt_x = nxt_r.top()[1], nxt_y = nxt_r.top()[2]; nxt_r.pop(); color[nxt_x][nxt_y] = 1; if(ad_b.count({nxt_x,nxt_y})) adj = 1; else{ for(int i = 0; i < 4; i++){ int ad_x = nxt_x + dx[i], ad_y = nxt_y + dy[i]; if(!ad_r.count({ad_x,ad_y}) && color[ad_x][ad_y] == -1){ nxt_r.push({-A[ad_x][ad_y],ad_x,ad_y}); ad_r.insert({ad_x,ad_y}); } } } } else { int nxt_x = nxt_b.top()[1], nxt_y = nxt_b.top()[2]; nxt_b.pop(); color[nxt_x][nxt_y] = 0; if(ad_r.count({nxt_x,nxt_y})) adj = 1; else{ for(int i = 0; i < 4; i++){ int ad_x = nxt_x + dx[i], ad_y = nxt_y + dy[i]; if(!ad_b.count({ad_x,ad_y}) && color[ad_x][ad_y] == -1){ nxt_b.push({-A[ad_x][ad_y],ad_x,ad_y}); ad_b.insert({ad_x,ad_y}); } // nxt_b.push({-A[ad_x][ad_y],ad_x,ad_y}); } } } } // output cout << ans << endl; }