#include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; struct Node { int y; int x; vector path; Node(int y = -1, int x = -1) { this->y = y; this->x = x; this->path.clear(); } bool operator>(const Node &n) const { return path.size() > n.path.size(); } }; const int DY[4] = {-1, 0, 1, 0}; const int DX[4] = {0, 1, 0, -1}; bool is_kadomatsu(int a1, int a2, int a3) { if (a1 == a2) return false; if (a1 == a3) return false; if (a2 == a3) return false; if (a1 < a2 && a2 < a3) return false; if (a1 > a2 && a2 > a3) return false; return true; } int main() { int W, H; cin >> W >> H; int M[H][W]; for (int y = 0; y < H; ++y) { for (int x = 0; x < W; ++x) { cin >> M[y][x]; } } priority_queue , greater> pque; Node root(0, 0); root.path.push_back(M[0][0]); pque.push(root); bool visited[H][W][10]; memset(visited, false, sizeof(visited)); while (not pque.empty()) { Node node = pque.top(); pque.pop(); int l = node.path.size(); if (l >= 2) { if (visited[node.y][node.x][node.path[l - 2]]) continue; visited[node.y][node.x][node.path[l - 2]] = true; } if (node.y == H - 1 && node.x == W - 1) { cout << node.path.size() - 1 << endl; return 0; } for (int dir = 0; dir < 4; ++dir) { int ny = node.y + DY[dir]; int nx = node.x + DX[dir]; if (ny < 0 || nx < 0 || H <= ny || W <= nx) continue; Node next(ny, nx); next.path = node.path; next.path.push_back(M[ny][nx]); int l = next.path.size(); if (l >= 3) { if (not is_kadomatsu(next.path[l - 1], next.path[l - 2], next.path[l - 3])) continue; } pque.push(next); } } cout << -1 << endl; return 0; }