#include using namespace std; const int dx[] = {1, 0, -1, 0}; const int dy[] = {0, -1, 0, 1}; int main() { int W, H, M[110][110] = {}; cin >> W >> H; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> M[j][i]; } } int dp[110][110][4] = {}; for (int i = 0; i < 105; i++) { for (int j = 0; j < 105; j++) { for (int k = 0; k < 4; k++) { dp[i][j][k] = 1e5; } } } struct book { int x, y, bef; }; dp[1][0][2] = 1; dp[0][1][1] = 1; queue que; que.push({1, 0, 2}); que.push({0, 1, 1}); while (!que.empty()) { auto B = que.front(); que.pop(); int nx = B.x, ny = B.y, ns = B.bef; int bx = nx + dx[B.bef], by = ny + dy[B.bef]; for (int i = 0; i < 4; i++) { int nxt_x = nx + dx[i], nxt_y = ny + dy[i]; int nxt_step = dp[nx][ny][ns] + 1; if (nxt_x < 0 || nxt_x >= H || nxt_y < 0 || nxt_y >= W) continue; if (M[bx][by] == M[nxt_x][nxt_y]) continue; if (dp[nxt_x][nxt_y][(i + 2) % 4] <= nxt_step) continue; if ((M[nx][ny] - M[bx][by]) * (M[nx][ny] - M[nxt_x][nxt_y]) <= 0) continue; dp[nxt_x][nxt_y][(i + 2) % 4] = nxt_step; que.push({nxt_x, nxt_y, (i + 2) % 4}); } } int ans = 1e5; for (int i = 0; i < 4; i++) { ans = min(ans, dp[H - 1][W - 1][i]); } if (ans >= 1e5) ans = -1; cout << ans << endl; }