from queue import PriorityQueue W,H = list(map(int, input().split(' '))) G = [] for i in range(H): G.append(list(map(int, input().split(' ')))) distance = [] for i in range(H): for j in range(W): distance.append([[0 for _ in range(10)] for _ in range(W)]) def is_kadomatsu(prev,current,next): if prev == 0: return True return ((prev < current and next < current) or (current < prev and current < next)) and prev != next def dijkstra(): dx = [1, 0, -1, 0] dy = [0, 1, 0, -1] que = PriorityQueue() que.put((0,0,0,0)) distance[0][0][0] = 0 answer = -1 while not que.empty(): dist,last,x,y = que.get() if x == H-1 and y == W-1: answer = dist break for i in range(len(dx)): nx = x + dx[i] ny = y + dy[i] if 0 <= nx and 0 <= ny and nx < W and ny < H \ and distance[nx][ny][G[x][y]] != float('inf') \ and is_kadomatsu(last, G[x][y], G[nx][ny]): que.put((dist+1,G[x][y],nx,ny)) distance[nx][ny][G[x][y]] = dist+1 print(answer) dijkstra()