#!/usr/bin/env python def read(): col, row = map(int, raw_input().split()) b = [] for i in range(row): b.append(map(int, raw_input().split())) return row, col, b def isKadomatsu(a, b, c): if a == 0 or b == 0: return True return b > a > c or b > c > a or a > c > b or c > a > b def work((row, col, b)): # cost[r][c][A_0][A_1]: # of step cost = [[[[-1 for l in range(10)] for k in range(10)] for j in range(col)] for i in range(row)] Q = [] cost[0][0][0][b[0][0]] = 0 Q.append((0, 0, 0, b[0][0])) while Q: (r, c, A0, A1) = Q[0] del Q[0] if r == row - 1 and c == col - 1: print cost[r][c][A0][A1] return for (dr, dc) in [(-1, 0), (0, 1), (1, 0), (0, -1)]: nr = r + dr nc = c + dc if not (0 <= nr < row and 0 <= nc < col): continue if not isKadomatsu(A0, A1, b[nr][nc]): continue if cost[nr][nc][A1][b[nr][nc]] != -1: continue cost[nr][nc][A1][b[nr][nc]] = cost[r][c][A0][A1] + 1 Q.append((nr, nc, A1, b[nr][nc])) print -1 if __name__ == "__main__": work(read())