from collections import deque def is_kadomatsu(a, b, c): if a == b or b == c or a == c: return False sorted_vals = sorted([a, b, c], reverse=True) mid = sorted_vals[1] return mid == a or mid == c def main(): import sys input = sys.stdin.read().split() ptr = 0 W = int(input[ptr]) ptr += 1 H = int(input[ptr]) ptr += 1 grid = [] for y in range(H): row = list(map(int, input[ptr:ptr+W])) ptr += W grid.append(row) start_x, start_y = 0, 0 goal_x, goal_y = W-1, H-1 if start_x == goal_x and start_y == goal_y: print(0) return visited = [[[[False for _ in range(10)] for __ in range(10)] for ___ in range(W)] for ____ in range(H)] directions = [ (0, 1), (1, 0), (0, -1), (-1, 0) ] queue = deque() initial_val = grid[start_y][start_x] for dx, dy in directions: new_x = start_x + dx new_y = start_y + dy if 0 <= new_x < W and 0 <= new_y < H: next_val = grid[new_y][new_x] if not visited[new_y][new_x][initial_val][next_val]: visited[new_y][new_x][initial_val][next_val] = True queue.append( (new_x, new_y, initial_val, next_val, 1) ) found = -1 while queue: x, y, pv, cv, steps = queue.popleft() if x == goal_x and y == goal_y: found = steps break for dx, dy in directions: new_x = x + dx new_y = y + dy if 0 <= new_x < W and 0 <= new_y < H: new_val = grid[new_y][new_x] if not is_kadomatsu(pv, cv, new_val): continue if not visited[new_y][new_x][cv][new_val]: visited[new_y][new_x][cv][new_val] = True queue.append( (new_x, new_y, cv, new_val, steps + 1) ) print(found if found != -1 else -1) if __name__ == '__main__': main()