#include using namespace std; const int INF = 1 << 25; int dy[] = {0, 0, 1, -1}; int dx[] = {1, -1, 0, 0}; int W, H, M[111][111]; int dist[111][111][11]; struct State { int y, x, pre; }; bool is_kadomatu(int a, int b, int c){ if(a < b && c < b && a != c) return true; if(a > b && c > b && a != c) return true; return false; } int main(){ cin >> W >> H; for(int i=0;i> M[i][j]; for(int i=0;i Q; // first step for(int i=0;i<4;i++){ int pre = M[0][0]; int ny = dy[i]; int nx = dx[i]; if(ny < 0 || nx < 0 || ny >= H || nx >= W) continue; if(M[ny][nx] == pre) continue; dist[ny][nx][pre] = 1; Q.push(State{ny, nx, pre}); } while(!Q.empty()){ auto st = Q.front(); Q.pop(); int y = st.y; int x = st.x; int pre = st.pre; int crr = M[y][x]; int cost = dist[y][x][pre]; for(int i=0;i<4;i++){ int ny = y + dy[i]; int nx = x + dx[i]; int nc = cost + 1; if(ny < 0 || nx < 0 || ny >= H || nx >= W) continue; if(!is_kadomatu(pre, crr, M[ny][nx])) continue; if(nc >= dist[ny][nx][crr]) continue; dist[ny][nx][crr] = nc; Q.push(State{ny, nx, crr}); } } int res = INF; for(int k=1;k<=9;k++) res = min(res, dist[H-1][W-1][k]); if(res >= INF) res = -1; cout << res << endl; return 0; }