#include #include #include #include #include #include #include #include #include #include #include #define PI 3.14159265359 #define INF 99999999; #define rep(i, n) for(int i=0; i draw(int n) { } }; */ class Pos { public: //書かれている数字 int num; int x, y, cnt; int pre; Pos(int pnum, int px, int py, int pcnt, int ppre) { num = pnum; x = px; y = py; cnt = pcnt; pre = ppre; } }; int dx[] = {1, -1, 0, 0}; int dy[] = {0, 0, 1, -1}; int main() { int W, H, M[100][100]; bool bM[110][110] = {false}; cin >> W >> H; rep(i, H) rep(j, W) cin >> M[i][j]; bool flag = false; queue q; q.push(Pos(M[0][0], 0, 0, 0, 0)); q.push(Pos(M[0][0], 0, 0, 0, 10)); bM[0][0] = true; while (!q.empty()) { Pos now = q.front(); q.pop(); if (now.x == W - 1 && now.y == H - 1) { cout << now.cnt << endl; flag = true; break; } for (int i=0; i<4; i++) { int nx = now.x + dx[i]; int ny = now.y + dy[i]; if (0<=nx && nx now.num) { Pos next = Pos(M[ny][nx], nx, ny, now.cnt + 1, now.num); bM[ny][nx] = true; q.push(next); } } } } } if (!flag) { cout << -1 << endl; } return 0; }