from collections import * from itertools import * from functools import * from heapq import * import sys,math input = sys.stdin.readline W,H = map(int,input().split()) A = [list(map(int,input().split())) for _ in range(H)] INF = (1<<30) dp = [[[INF]*W for i in range(H)] for j in range(10)] v = deque() dp[A[0][0]][0][1]=1 dp[A[0][0]][1][0]=1 v.append((0,1,A[0][0])) v.append((1,0,A[0][0])) def nb(x,y): tmp = [] if x+1=0: tmp.append((x-1,y)) if y+1=0: tmp.append((x,y-1)) return tmp while v: x,y,b = v.popleft() a = A[x][y] base = dp[b][x][y] for ix,iy in nb(x,y): c = A[ix][iy] X = [b,a,c] Y = X[:] Y.sort() if len(set(Y))!=3: continue if Y[1]!=X[1]: if dp[a][ix][iy]!=INF: continue dp[a][ix][iy] = base + 1 v.append((ix,iy,a)) ans = min(dp[i][-1][-1] for i in range(10)) if ans==INF: print(-1) else: print(ans)