w,h,*b = map(int,open(0).read().split()) M = 2**15 from collections import deque q = deque() d = {} for i in [1,w]: if b[0] != b[i]: q.append(i*M) d[i*M] = 1 def check(c,x2,delta): if c*M+x2 in d: return if delta*(b[c]-b[x2]) < 0: q.append(c*M+x2) d[c*M+x2] = d[x] + 1 while q: x = q.popleft() x1,x2 = x%M, x//M h2,w2 = x2//w, x2%w delta = b[x2] - b[x1] if h2: check(x2-w,x2,delta) if h2+1 < h: check(x2+w,x2,delta) if w2: check(x2-1,x2,delta) if w2+1 < w: check(x2+1,x2,delta) ans = INF = 10**9 for c in [(w*h-1)*M + (w*h-2), (w*h-1)*M + (w*h-1-w)]: if c in d: ans = min(ans,d[c]) print(ans if ans != INF else -1)