#include using namespace std; namespace { typedef double real; typedef long long ll; template ostream& operator<<(ostream& os, const vector& vs) { if (vs.empty()) return os << "[]"; auto i = vs.begin(); os << "[" << *i; for (++i; i != vs.end(); ++i) os << " " << *i; return os << "]"; } template istream& operator>>(istream& is, vector& vs) { for (auto it = vs.begin(); it != vs.end(); it++) is >> *it; return is; } int W, H; vector> M; void input() { cin >> W >> H; M = vector>(H, vector(W, 0)); cin >> M; } const int dy[] = {-1, 0, 1, 0}; const int dx[] = {0, 1, 0, -1}; const int INF = 1<<28; struct S { int y, x, p, q; int c; S() {} S(int y, int x, int p, int q, int c) : y(y), x(x), p(p), q(q), c(c) {} }; ostream& operator<<(ostream& os, const S& s) { return os << "S[(" << s.y << "," << s.x << " " << s.p << " " << s.q << ") -> " << s.c << "]"; } void solve() { int D[H][W][12][12]; for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) for (int k = 0; k < 12; k++) for (int l = 0; l < 12; l++) D[i][j][k][l] = INF; queue Q; Q.emplace(0, 0, 0, 11, 0); Q.emplace(0, 0, 11, 0, 0); D[0][0][0][11] = 0; D[0][0][11][0] = 0; while (not Q.empty()) { S cur = Q.front(); Q.pop(); //cout << cur << endl; for (int i = 0; i < 4; i++) { int ny = cur.y + dy[i]; int nx = cur.x + dx[i]; int np = M[cur.y][cur.x]; int nq = cur.p; int nc = cur.c + 1; if (ny < 0 || ny >= H) continue; if (nx < 0 || nx >= W) continue; int cp = M[ny][nx]; if ( (nq - cp) * (np - cp) >= 0 && (np - nq) * (cp - nq) >= 0 ) continue; // kadomatsu? int& cur_best = D[ny][nx][np][nq]; if (cur_best > nc) { cur_best = nc; Q.emplace(ny, nx, np, nq, nc); } } } int ans = INF; for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { ans = min(ans, D[H - 1][W - 1][i][j]); } } if (ans == INF) ans = -1; cout << ans << endl; } } int main() { input(); solve(); return 0; }