#include #include #include #include #include using namespace std; typedef long long ll; typedef pair P; typedef pair PP; int W, H; int M[100][100]; int dx[4] = { -1, 0, 1, 0 }; int dy[4] = { 0, 1, 0, -1 }; int d[100][100] = { 0 }; bool isKadomatsu(int a, int b, int c) { if (a == 0 || b == 0) return true; if ((a == b) || (b == c) || (a == c)) { return false; } else { return !(((a < b) && (b < c)) || ((a > b) && (b > c))); } } int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> W >> H; int k = 0; for (int i = 0; i < W; i++) { for (int j = 0; j < H; j++) { cin >> M[i][j]; } } for (int i = 0; i < W; i++) { for (int j = 0; j < H; j++) { d[i][j] = -1; } } d[0][0] = 0; queue que; que.push(PP(P(0, 0), P(0, 0))); while (que.size() && k <= 1000000) { PP p = que.front(); que.pop(); for (int i = 0; i < 4; i++) { int nx = p.first.first + dx[i]; int ny = p.first.second + dy[i]; int b = M[p.first.first][p.first.second]; int bb = p.second.second; if (0 <= nx && nx < W && 0 <= ny && ny < H) { if (isKadomatsu(bb, b, M[nx][ny])) { que.push(PP(P(nx, ny), P(bb, b))); d[nx][ny] = d[p.first.first][p.first.second] + 1; } } } if (d[W - 1][H - 1] != -1) break; k++; } cout << d[W - 1][H - 1]; return 0; }