// yukicoder 124 (http://yukicoder.me/problems/222) #include #include #include #include #define rep(i,a) for(int i=0;i<(a);++i) typedef std::pair P; const int MAX_H = 100, MAX_W = 100, dr[5] = { 0, -1, 0, 1, 0 }, INF = std::numeric_limits::max()>>2; struct St { P p; int prv, dist; St( const P &p, int prv, int dist ) : p(p), prv(prv), dist(dist) {} }; int W, H; int M[MAX_H][MAX_W], dist[9][MAX_H][MAX_W]; bool isKS( int a, int b, int c ) { int ar[3] = {a,b,c}; std::sort( ar, ar+3 ); return ar[1] != b; } int main() { scanf( "%d%d", &W, &H ); rep( i, H ) rep( j, W ) scanf( "%d", &M[i][j] ), --M[i][j]; rep( i, 9 ) rep( j, H ) rep( k, W ) dist[i][j][k] = INF; dist[0][0][0] = 0; std::queue que; que.push( St( P(0,0), 0, 0 ) ); while( !que.empty() ) { St st = que.front(); que.pop(); int i = st.p.first, j = st.p.second; rep( d, 4 ) { int ni = i+dr[d], nj = j+dr[d+1]; if( dist[M[i][j]][ni][nj] != INF ) continue; if( st.prv && !isKS( M[ni][nj], M[i][j], st.prv ) ) continue; if( ni >= 0 && ni < H && nj >= 0 && nj < W ) { que.push( St( P(ni,nj), M[i][j], st.dist+1 ) ); dist[M[i][j]][ni][nj] = st.dist+1; } } } int ans = INF; rep( i, 9 ) ans = std::min( ans, dist[i][H-1][W-1] ); printf( "%d\n", ans==INF?-1:ans ); return 0; }