#include #include #include #include #include using namespace std; typedef long long ll; typedef pair P; #define rep(i,n) for(int i=0;i<(n);i++) const int INF = 1e9; int dy[] = {1, 0, -1, 0}; int dx[] = {0, 1, 0, -1}; int h, w; int board[110][110]; //d[i][j] := (x, y)へいく最短距離 int d[110][110]; int main(void){ cin >> h >> w; rep(i, h)rep(j, w) cin >> board[i][j]; rep(i, h)rep(j, w) d[i][j] = INF; queue > q; q.push(make_pair(make_pair(0, 1), make_pair(0, 0))); q.push(make_pair(make_pair(1, 0), make_pair(0, 0))); d[0][0] = 0; d[0][1] = 1; d[1][0] = 1; while(!q.empty()){ auto p1 = q.front().first;//1つ前 auto p2 = q.front().second;//2つ前 q.pop(); rep(i, 4){ int ny = p1.first + dy[i], nx = p1.second + dx[i]; if(ny == h - 1 && nx == w - 1) break; if(!(0 <= ny && ny < h && 0 <= nx && nx < w)) continue; if(d[ny][nx] != INF) continue; int len0 = board[ny][nx]; int len1 = board[p1.first][p1.second]; int len2 = board[p2.first][p2.second]; if(len0 == len1 || len1 == len2 || len2 == len0) continue; int mid = (len0 + len1 + len2) - min(len0, min(len1, len2)) - max(len0, max(len1, len2)); if(mid == len0 || mid == len2){ q.push(make_pair(make_pair(ny, nx), p1)); d[ny][nx] = d[p1.first][p1.second] + 1; } } } int ans = d[h - 1][w - 1]; if(ans == INF) printf("-1\n"); else printf("%d\n", d[h - 1][w - 1]); return 0; }