#include #include #include #include #define repeat(i,n) for (int i = 0; (i) < (n); ++(i)) using namespace std; template auto vectors(T a, X x) { return vector(x, a); } template auto vectors(T a, X x, Y y, Zs... zs) { auto cont = vectors(a, y, zs...); return vector(x, cont); } const int inf = 1e9+7; const int dy[] = { -1, 1, 0, 0 }; const int dx[] = { 0, 0, 1, -1 }; struct state_t { int y, x, last, dist; }; bool operator < (state_t const & a, state_t const & b) { return a.dist > b.dist; } // reversed, weak bool is_kadomatsu_sequence(int a, int b, int c) { if (a == 0) return true; return ((a < b and b > c) or (a > b and b < c)) and a != c; } int main() { int w, h; cin >> w >> h; vector > m = vectors(int(), h, w); repeat (y,h) repeat (x,w) cin >> m[y][x]; repeat (y,h) repeat (x,w) assert (1 <= m[y][x] and m[y][x] <= 9); auto is_on_field = [&](int y, int x) { return 0 <= y and y < h and 0 <= x and x < w; }; vector > > dist = vectors(inf, h, w, 10); priority_queue que; { state_t a; a.y = 0; a.x = 0; a.last = 0; a.dist = 0; que.push(a); } int ans = -1; while (not que.empty()) { state_t a = que.top(); que.pop(); if (a.y == h-1 and a.x == w-1) { ans = a.dist; break; } repeat (i,4) { state_t b = a; b.y += dy[i]; b.x += dx[i]; b.last = m[a.y][a.x]; b.dist += 1; if (not is_on_field(b.y, b.x)) continue; if (not is_kadomatsu_sequence(a.last, b.last, m[b.y][b.x])) continue; if (dist[b.y][b.x][b.last] != inf) continue; dist[b.y][b.x][b.last] = b.dist; que.push(b); } } cout << ans << endl; return 0; }