//#include "bits/stdc++.h" #include #include #include #include using namespace std; #define REP(i,n) for(int i=0;i<(int)n;++i) #define ALL(c) (c).begin(), (c).end() int dp[100][100][10]; int INF = 99999999; int dx[4]{1, 0, -1, 0}; int dy[4]{0, 1, 0, -1}; bool check(int a, int b, int c){ vector v; v.push_back(a); v.push_back(b); v.push_back(c); sort(v.begin(), v.end()); if (v[0] == v[1]) return false; if (v[1] == v[2]) return false; if (v[1] == b) return false; return true; } int main() { int W, H; cin >> W >> H; vector> board(H, vector(W)); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> board[i][j]; } } for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { for (int k = 0; k < 10; k++) { dp[i][j][k] = INF; } } } queue, int>> q; for (int k = 0; k < 10; k++) { dp[0][0][k] = 0; q.push(make_pair(make_pair(0, 0), k)); } while (!q.empty()){ auto pos = q.front().first; auto pre = q.front().second; q.pop(); int now = board[pos.first][pos.second]; int cost = dp[pos.first][pos.second][pre]; for (int k = 0; k < 4; k++) { int ny = pos.first + dy[k]; int nx = pos.second + dx[k]; if (ny < 0 || ny >= H || nx < 0 || nx >= W) continue; int next = board[ny][nx]; if (cost != 0 && !check(pre, now, next)) continue; if (dp[ny][nx][now] != INF) continue; dp[ny][nx][now] = cost + 1; q.push(make_pair(make_pair(ny, nx), now)); } } int ans = INF; for (int k = 0; k < 10; k++) { ans = min(ans, dp[H - 1][W - 1][k]); } if (ans == INF) ans = -1; cout << ans << endl; }