#include #include #include #include #include #include #include #include #include #include #include #include #include #include #define INF 1000000000 using namespace std; typedef long long ll; const int dx[] = {1, 0, -1, 0}; const int dy[] = {0, 1, 0, -1}; const int MAXH = 110; const int MAXW = 110; int M[MAXH][MAXW]; int d[12][MAXH][MAXW]; struct state{ int before; int cost; int y; int x; }; bool isKM(int a, int b, int c) { if (a == 0 || b == 0 || c == 0) return true; if (a == b || b == c || c == a) return false; if (b < a && b < c) return true; if (b > a && b > c) return true; return false; } int main(void) { int W, H; cin >> W >> H; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> M[i][j]; for (int k = 0; k < 12; k++) { d[k][i][j] = INF; } } } d[0][0][0] = 0; queue que; state s; s.before = 0; s.cost = 0; s.y = 0; s.x = 0; que.push(s); while (!que.empty()) { state now = que.front(); que.pop(); for (int k = 0; k < 4; k++) { int nx = now.x + dx[k]; int ny = now.y + dy[k]; if (nx < 0 || nx >= W || ny < 0 || ny >= H) continue; if (!isKM(now.before, M[now.y][now.x], M[ny][nx])) continue; if (d[M[now.y][now.x]][ny][nx] < INF) continue; d[M[now.y][now.x]][ny][nx] = now.cost + 1; state next; next.before = M[now.y][now.x]; next.cost = now.cost + 1; next.y = ny; next.x = nx; que.push(next); } } int ans = INF; for (int i = 0; i < 12; i++) { ans = min(ans, d[i][H-1][W-1]); } if (ans == INF) ans = -1; cout << ans << endl; return 0; }