#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,pre typedef tuple State; typedef tuple ns; map dp; int solve(){ dp.clear(); dp[mt(0,-1)] = 0; priority_queue q; q.emplace(0,0,-1); while(q.size()){ int d,v,p; tie(d,v,p) = q.top(); q.pop(); d = -d; if(v==W*H-1) return d; int dx[]={0,1,-1,0}, dy[]={1,0,0,-1}; if(dp.count(tie(v,p)) && dp[tie(v,p)] < d) continue; rep(i,4){ int nx = v%W+dx[i], ny = v/W+dy[i]; int x = v%W, y = v/W; int px = p%W, py = p/W; if(nx < 0 || nx >= W || ny < 0 || ny >= H) continue; if(p==-1){ if(M[y][x]==M[ny][nx]){ continue; } } else { if(M[py][px] == M[ny][nx]) continue; if(!((M[py][px] < M[y][x] && M[y][x] > M[ny][nx]) || (M[py][px] > M[y][x] && M[y][x] < M[ny][nx]))){ continue; } } int nv = ny*W+nx; if(dp.count(tie(nv,v))==0 || dp[tie(nv,v)] > d+1){ dp[tie(nv,v)] = d+1; q.emplace(-(d+1),nv,v); } } } return -1; } int main(){ while(cin>>W>>H && W){ rep(i,H)rep(j,W) cin >> M[i][j]; cout << solve() << endl; } }