#include using namespace std; template bool cmin(T &a, U b) { return a > b && (a = b, true); } template bool cmax(T &a, U b) { return a < b && (a = b, true); } template class Dijkstra { private: struct edge { int to; T cost; }; vector> G; vector D; public: Dijkstra(int n) : G(n), D(n, numeric_limits::max()) {} void add(int from, int to, T cost) { G.at(from).push_back((edge){to, cost}); } vector solve(int start) { using pti = pair; priority_queue, greater> Q; D.at(start) = 0; Q.push(pti(0, start)); while (Q.size()) { auto [dist, now] = Q.top(); Q.pop(); if (D.at(now) < dist) continue; for (auto [next, cost] : G.at(now)) { if (D.at(next) > D.at(now) + cost) { D.at(next) = D.at(now) + cost; Q.push(pti(D.at(next), next)); } } } return D; } void reset() { fill(D.begin(), D.end(), numeric_limits::max()); } }; signed main() { cin.tie(nullptr); ios_base::sync_with_stdio(false); int W, H; cin >> W >> H; vector> S(H, vector(W)); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> S.at(i).at(j); } } Dijkstra D(H * W * 10); auto id = [&](int h, int w) { return W * h + w; }; auto iskd = [&](int a, int b, int c) { if (a == b || b == c || c == a) return false; if (b == max({a, b, c})) return true; if (b == min({a, b, c})) return true; return false; }; vector mh{-1, 0, 1, 0}; vector mw{0, 1, 0, -1}; for (int h = 0; h < H; h++) { for (int w = 0; w < W; w++) { for (int i = 0; i < 4; i++) { int nh = h + mh.at(i); int nw = w + mw.at(i); if (nh < 0 || nh >= H || nw < 0 || nw >= W) continue; for (int a = 1; a <= 9; a++) { int b = S.at(h).at(w) - '0'; int c = S.at(nh).at(nw) - '0'; if (iskd(a, b, c)) D.add(H * W * a + id(h, w), H * W * b + id(nh, nw), 1); else if (!h && !w) D.add(H * W * a + id(h, w), H * W * b + id(nh, nw), 1); } } } } int ans = INT_MAX; for (int i = 1; i <= 9; i++) { auto tmp = D; auto V = tmp.solve(H * W * i); for (int j = 1; j <= 9; j++) { cmin(ans, V.at(H * W * j + id(H - 1, W - 1))); } } if (ans == INT_MAX) ans = -1; cout << ans << "\n"; }