#include #include #include #include #include #include #include #include #include #define repd(i,a,b) for (int i=(a);i<(b);i++) #define rep(i,n) repd(i,0,n) typedef long long ll; using namespace std; int inputValue(){ int a; cin >> a; return a; }; void inputArray(int * p, int a){ rep(i, a){ cin >> p[i]; } }; void inputVector(vector * p, int a){ rep(i, a){ int input; cin >> input; p -> push_back(input); } } template void output(T a, int precision) { if(precision > 0){ cout << setprecision(precision) << a << "\n"; } else{ cout << a << "\n"; } } bool isKado(int a, int b, int c){ if ((c < a && a < b) || (b < a && a < c) || (a < c && c < b) || (b < c && c < a)) { return true; } else{ return false; } } int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; // int main(int argc, const char * argv[]) { // source code int W = inputValue(); // 2以上 int H = inputValue(); // 2以上 vector > M(W, vector(H)); vector > C(W, vector(H)); //最短 //vector > V(W, vector(H)); //通ったか bool V[200][200][4]; rep(j, H){ rep(i, W){ M[i][j] = inputValue(); // V[i][j] = false; C[i][j] = 0; rep(k, 4){ V[i][j][k] = false; } } } queue, pair>> q; if (H >= 3) { if (isKado(M[0][0], M[0][1], M[0][2])) { //q.push(make_pair(make_pair(0, 2), M[0][1])); q.push(make_pair(make_pair(0, 2), make_pair(0, 1))); C[0][2] = 2; V[0][1][2] = true; V[0][2][2] = true; } } if (isKado(M[0][0], M[0][1], M[1][1])) { q.push(make_pair(make_pair(1, 1),make_pair(0, 1))); C[1][1] = 2; V[0][1][2] = true; V[1][1][0] = true; } if (isKado(M[0][0], M[1][0], M[1][1])) { q.push(make_pair(make_pair(1, 1), make_pair(1, 0))); C[1][1] = 2; V[1][0][0] = true; V[1][1][2] = true; } if (W >= 3) { if (isKado(M[0][0], M[1][0], M[2][0])) { q.push(make_pair(make_pair(2, 0), make_pair(1, 0))); C[2][0] = 2; V[1][0][0] = true; V[2][0][0] = true; } } while (!q.empty()) { int x = q.front().first.first; int y = q.front().first.second; int prevM = M[q.front().second.first][q.front().second.second]; q.pop(); // V[x][y] = true; rep(i, 4){ int nx = x + dx[i]; int ny = y + dy[i]; if (nx < 0 || nx >= W || ny < 0 || ny >= H || V[nx][ny][i]) { continue; } if (isKado(prevM, M[x][y], M[nx][ny])) { q.push(make_pair(make_pair(nx, ny), make_pair(x, y))); C[nx][ny] = C[x][y] + 1; V[nx][ny][i] = true; if (nx == W - 1 && ny == H - 1) { break; } } } } output((C[W - 1][H - 1] != 0) ? C[W - 1][H - 1] : -1, 0); return 0; }