#include using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int H,W; cin >> H >> W; vector> A(H,vector(W)); for(int i=0; i> A.at(i).at(k); vector> alr(H,vector(W)),alb = alr; priority_queue,vector>,greater<>> qr,qb; bool end = false; int answer = -2; qr.push({0,0,0}),qb.push({0,H-1,W-1}); vector> dxy = {{-1,0},{0,1},{1,0},{0,-1}}; while(true){ auto[a,x,y] = qr.top(); qr.pop(); while(alr.at(x).at(y)){tie(a,x,y) = qr.top(); qr.pop();} alr.at(x).at(y) = true; answer++; for(auto &[dx,dy] : dxy){ int nx = x+dx,ny = y+dy; if(nx < 0 || nx >= H || ny < 0 || ny >= W) continue; if(alr.at(nx).at(ny)) continue; if(alb.at(nx).at(ny)){end = true; break;} qr.push({A.at(nx).at(ny),nx,ny}); } if(end) break; tie(a,x,y) = qb.top(); qb.pop(); while(alb.at(x).at(y)){tie(a,x,y) = qb.top(); qb.pop();} alb.at(x).at(y) = true; answer++; for(auto &[dx,dy] : dxy){ int nx = x+dx,ny = y+dy; if(nx < 0 || nx >= H || ny < 0 || ny >= W) continue; if(alb.at(nx).at(ny)) continue; if(alr.at(nx).at(ny)){end = true; break;} qb.push({A.at(nx).at(ny),nx,ny}); } if(end) break; } cout << answer << endl; }