#define _CRT_SECURE_NO_WARNINGS #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; typedef vector vi; typedef vector vvi; typedef pair pii; #define all(c) (c).begin(), (c).end() #define loop(i,a,b) for(ll i=a; iDUMP &operator,(const T&t){if(this->tellp())*this<<", ";*this< ostream& operator<<(ostream& os, vector const& v){ rep(i,v.size()) os << v[i] << (i+1==v.size()?"":" "); return os; } int W,H; int M[111][111]; // d,v,pre1,pre2 typedef tuple State; typedef tuple ns; map dp; int solve(){ dp.clear(); dp[mt(0,-1,-1)] = 0; priority_queue q; q.emplace(0,0,-1,-1); while(q.size()){ int d,v,p1,p2; tie(d,v,p1,p2) = q.top(); q.pop(); //dump(d,v,p1,p2); d = -d; if(v==W*H-1) return d; int dx[]={0,1,-1,0}, dy[]={1,0,0,-1}; rep(i,4){ int nx = v%W+dx[i], ny = v/W+dy[i]; int x = v%W, y = v/W; int p1x = p1%W, p1y = p1/W; if(nx < 0 || nx >= W || ny < 0 || ny >= H) continue; if(p1==-1){ if(M[y][x]==M[ny][nx]){ continue; } } else { if(!((M[p1y][p1x] < M[y][x] && M[y][x] > M[ny][nx]) || (M[p1y][p1x] > M[y][x] && M[y][x] < M[ny][nx]))){ continue; } } int nv = ny*W+nx; if(dp.count(tie(nv,v,p1))==0 || dp[tie(nv,v,p1)] > d+1){ dp[tie(nv,v,p1)] = d+1; q.emplace(-(d+1),nv,v,p1); } } } throw ""; return -1; } int main(){ while(cin>>W>>H && W){ rep(i,H)rep(j,W) cin >> M[i][j]; cout << solve() << endl; } }