#include using namespace std; using VS = vector; using LL = long long; using VI = vector; using VVI = vector; using PII = pair; using PLL = pair; using VL = vector; using VVL = vector; #define ALL(a) begin((a)),end((a)) #define RALL(a) (a).rbegin(), (a).rend() #define PB push_back #define EB emplace_back #define MP make_pair #define SZ(a) int((a).size()) #define SORT(c) sort(ALL((c))) #define RSORT(c) sort(RALL((c))) #define UNIQ(c) (c).erase(unique(ALL((c))), end((c))) #define FOR(i, s, e) for (int(i) = (s); (i) < (e); (i)++) #define FORR(i, s, e) for (int(i) = (s); (i) > (e); (i)--) #define debug(x) cerr << #x << ": " << x << endl const int INF = 1e9; const LL LINF = 1e16; const LL MOD = 1000000007; const double PI = acos(-1.0); int DX[8] = { 0, 0, 1, -1, 1, 1, -1, -1 }; int DY[8] = { 1, -1, 0, 0, 1, -1, 1, -1 }; /* ----- 2018/04/26 Problem: yukicoder 124 / Link: http://yukicoder.me/problems/no/124 ----- */ /* ------問題------ -----問題ここまで----- */ /* -----解説等----- ----解説ここまで---- */ int main() { cin.tie(0); ios_base::sync_with_stdio(false); int W, H; cin >> H >> W; VVI a(H, VI(W)); FOR(i, 0, H) { FOR(j, 0, W) { cin >> a[i][j]; } } int dist[102][102][10][10]; fill(***dist, ***dist + 102 * 102 * 10 * 10, INF); using tp = tuple; queuepq; dist[0][0][0][a[0][0]] = 0; pq.push(tp(0, 0, 0, 0, a[0][0])); // dist, y, x, prepre, pre auto f = [&](int c, int b, int a) {// bool ok = 0; if (ac&&a != c)ok = 1; if (a > b&&b < c&&a != c)ok = 1; if (a == 0 || b == 0)ok = 1; return ok; }; while (!pq.empty()) { int d, y, x, a_2, a_1; tie(d, y, x, a_2, a_1) = pq.front(); pq.pop(); if (dist[y][x][a_2][a_1] < d)continue; FOR(k, 0, 4) { int ny = y + DY[k], nx = x + DX[k]; if (0 <= ny&&ny < H && 0 <= nx&&nx < W) { if (f(a[ny][nx], a_1, a_2)) { if (dist[ny][nx][a_1][a[ny][nx]] > dist[y][x][a_2][a_1] + 1) { dist[ny][nx][a_1][a[ny][nx]] = dist[y][x][a_2][a_1] + 1; pq.push(tp(d, ny, nx, a_1, a[ny][nx])); } } } } } int ans = INF; FOR(i, 1, 10) { FOR(j, 1, 10) { ans = min(ans, dist[H - 1][W - 1][i][j]); } } cout << (ans < INF ? ans : -1) << "\n"; return 0; }