#include using namespace std; #define all(c) (c).begin(),(c).end() #define rrep(i,n) for(int i=(int)(n)-1;i>=0;i--) #define REP(i,m,n) for(int i=(int)(m);i<(int)(n);i++) #define rep(i,n) REP(i,0,n) #define iter(c) __typeof((c).begin()) #define tr(it,c) for(iter(c) it=(c).begin();it!=(c).end();it++) #define pb(a) push_back(a) #define pr(a) cout<<(a)<> #define F first #define S second #define ll long long bool check(int n,int m,int x,int y){return (x<0||x>=n||y<0||y>=m)?false:true;} const ll MAX=1000000007,MAXL=1LL<<60,dx[4]={-1,0,1,0},dy[4]={0,-1,0,1}; typedef pair P; int main() { int n,m; R n >> m; int a[n][m]; rep(i,n) { rep(j,m) R a[i][j]; } int d[4][n][m]; rep(i,4)rep(j,n)rep(k,m) d[i][j][k]=MAX; d[0][0][0]=0; queue

que; queue di; que.push(P(0,0)); di.push(0); while(!que.empty()) { P p=que.front();que.pop(); int k=di.front();di.pop(); int nx=p.F,ny=p.S; rep(i,4) { int x=nx+dx[i],y=ny+dy[i]; if(!(check(n,m,x,y))) continue; if(nx==0 && ny==0) { if(d[i][x][y]>d[k][nx][ny]+1) { d[i][x][y]=d[k][nx][ny]+1; que.push(P(x,y)); di.push(i); } } else { int xx=nx-dx[k],yy=ny-dy[k]; int a1=a[xx][yy],a2=a[nx][ny],a3=a[x][y]; bool ck=false; if(a1a2 && a3>a2 && a1!=a2)ck=true; if(ck) { if(d[i][x][y]>d[k][nx][ny]+1) { d[i][x][y]=d[k][nx][ny]+1; que.push(P(x,y)); di.push(i); } } } } } int ans=MAX; rep(i,4) ans=min(ans,d[i][n-1][m-1]); if(ans==MAX) pr(-1); else pr(ans); return 0; }