import sys read=sys.stdin.buffer.read readline=sys.stdin.buffer.readline readlines=sys.stdin.buffer.readlines w, h=map(int, readline().split()) m=list(map(int, read().split())) from collections import deque que=deque() INF=10**9 dp=[[INF]*(w*h) for _ in range(4)] dp[0][0]=0 que.append((0, 0)) dx=[1, -1, 0, 0] dy=[0, 0, 1, -1] def is_kadomatsu(a, b, c): if a!=c and ((ac) or (a>b and b=h or y1<0 or y1>=w: continue xy1=x1*w+y1 if dp[i][xy1]>d+1 and (d==0 or is_kadomatsu(m[xy2], m[xy], m[xy1])): dp[i][xy1]=d+1 que.append((xy1, i)) ans=min(dp[0][-1], dp[2][-1]) if ans==INF: print(-1) else: print(ans)