#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][4]; struct State { int y, x, dir; }; 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][i] = 1; Q.push(State{ny, nx, i}); } while(!Q.empty()){ auto st = Q.front(); Q.pop(); int y = st.y; int x = st.x; int dir = st.dir; int py = y - dy[dir]; int px = x - dx[dir]; int pre = M[py][px]; int crr = M[y][x]; int cost = dist[y][x][dir]; 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][i]) continue; dist[ny][nx][i] = nc; Q.push(State{ny, nx, i}); } } int res = INF; for(int k=0;k<4;k++) res = min(res, dist[H-1][W-1][k]); if(res >= INF) res = -1; cout << res << endl; return 0; }