from collections import deque def iks(a, b, c): return a != c and ((a < b > c) or (a > b < c)) def main(): W, H = map(int, input().split()) M = [list(map(int, input().split())) for i in range(H)] Q = deque([(i, 0, 0) for i in range(1, 11)]) D = [[[None]*W for i in range(H)] for j in range(1, 11)] for i in range(1, 11): D[i][0][0] = 0 while len(Q) > 0: b, x, y = Q.popleft() if (x, y) == (H-1, W-1): print(D[b][x][y]) return for dx, dy in [(-1, 0), (1, 0), (0, 1), (0, -1)]: bv, r, c = M[x][y], x + dx, y + dy if 0 <= r < H and 0 <= c < W and D[bv][r][c] is None and iks(b, M[x][y], M[r][c]): D[bv][r][c] = D[b][x][y] + 1 Q.append((bv, r, c)) print(-1) return if __name__ == '__main__': main()