#include #include #include using namespace atcoder; using mint = modint998244353; using namespace std; #define rep(i,n) for (int i = 0; i < (n); ++i) #define Inf32 1000000001 #define Inf64 1000000000000000001 int main(){ int h,w; cin>>h>>w; vector> a(h,vector(w)); rep(i,h){ rep(j,w)cin>>a[i][j]; } map> mp; rep(i,h){ rep(j,w)mp[a[i][j]] = make_pair(i,j); } vector ans(h,vector(w,-1)); vector dx = {1,-1,0,0},dy = {0,0,1,-1}; vector,greater>> Q(2); rep(i,2){ int x = 0,y = 0; if(i)x = h-1,y = w-1; ans[x][y] = i; rep(j,4){ int xx = x+dx[j],yy = y+dy[j]; //cout<=h||yy>=w)continue; Q[i].push(a[xx][yy]); } } rep(_,10000000){ int i = _%2; while(true){ int u = Q[i].top(); Q[i].pop(); int x =mp[u].first,y = mp[u].second; if(ans[x][y]!=-1)continue; ans[x][y] = i; rep(j,4){ int xx = x+dx[j],yy = y+dy[j]; if(xx<0||xx>=h||yy<0||yy>=w)continue; if(ans[xx][yy]!=-1 && ans[xx][yy]!=i){ cout<<_+1<