#include #include #include #include #include using namespace std; typedef pair II; typedef pair, vector > History; typedef vector Queue; struct Solver { int H; int W; int b[100][100]; public: Solver(int h, int w, const int (&bb)[100][100]): H(h), W(w) { memcpy(b, bb, sizeof(b)); } int solve(void) { vector a; a.push_back(b[0][0]); Queue q; q.push_back(make_pair(II(0, 0), a)); int ans = 0; while (q.size() > 0 && ans < W*H) { Queue next; for (int i = 0; i < (int)q.size(); ++i) { const History &h = q[i]; if (h.first.first == W - 1 && h.first.second == H - 1) { return ans; } int len = (int)h.second.size(); const int dx[4] = { -1, 0, 1, 0 }; const int dy[4] = { 0, -1, 0, 1 }; for (int d = 0; d < 4; ++d) { int xx = h.first.first + dx[d], yy = h.first.second + dy[d]; if (xx >= 0 && xx < W && yy >= 0 && yy < H) { int n = b[yy][xx]; if (len <= 1 || (h.second[len - 2] < h.second[len - 1] && h.second[len-1] > n) || (h.second[len - 2] > h.second[len - 1] && h.second[len - 1] < n)) { vector b = h.second; b.push_back(n); next.push_back(make_pair(II(xx, yy), b)); } } } } q = next; ++ans; } return -1; } }; int main(int argc, char *argv[]) { int W, H; string s; { getline(cin, s); stringstream ss(s); ss >> W >> H; } int b[100][100] = {}; for (int i = 0; i < H; ++i) { getline(cin, s); stringstream ss(s); for (int j = 0; j < W; ++j) { ss >> b[i][j]; } } Solver solver(H, W, b); int ans = solver.solve(); cout << ans << endl; return 0; }