#include #include #include using namespace std; struct State { int x; int y; int previousValue; int steps; State(int x, int y, int previousValue, int steps) : x(x), y(y), previousValue(previousValue), steps(steps) { } }; const int dx[] = { 1, -1, 0, 0 }; const int dy[] = { 0, 0, 1, -1 }; bool isKadomatsuSequence(int a, int b, int c) { if (a < 0 || b < 0 || c < 0) { return true; } if (a != c) { if (a < b && b > c) { return true; } if (a > b && b < c) { return true; } } return false; } int main() { int w, h; cin >> w >> h; vector > m(w, vector(h)); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { cin >> m[x][y]; } } vector states; vector > shortest(w, vector(h, numeric_limits::max())); states.push_back(State(0, 0, -1, 0)); shortest[0][0] = states.back().steps; while (!states.empty()) { State top = states.back(); states.pop_back(); int topValue = m[top.x][top.y]; for (int d = 0; d < 4; ++d) { State next(top.x + dx[d], top.y + dy[d], topValue, top.steps + 1); if (0 <= next.x && next.x < w && 0 <= next.y && next.y < h && isKadomatsuSequence(top.previousValue, topValue, m[next.x][next.y]) && next.steps < shortest[next.x][next.y]) { shortest[next.x][next.y] = next.steps; if (next.x != w - 1 || next.y != h - 1) { states.push_back(next); } } } } cout << ( shortest[w - 1][h - 1] == numeric_limits::max() ? -1 : shortest[w - 1][h - 1] ) << endl; return 0; }