import sys #sys.setrecursionlimit(n) import heapq import re import bisect import random import math import itertools from collections import defaultdict, deque from copy import deepcopy from decimal import * w, h = map(int, input().split()) e = [[int(i) for i in input().split()] for _ in range(h)] v = defaultdict(lambda:defaultdict(lambda:defaultdict(lambda:defaultdict(lambda:defaultdict(lambda:defaultdict(list)))))) def solve(): q = deque() q.append((0 << 48) + (0 << 32) + (0 << 24) + (0 << 16) + (0 << 8) + 0) direction = ((0,1),(0,-1),(1,0),(-1,0)) while(q): qq = q.popleft() flag = qq >> 48 qc = (qq >> 32) & 0xFFFF qw2 = (qq >> 24) & 0xFF qh2 = (qq >> 16) & 0xFF qw = (qq >> 8) & 0xFF qh = qq & 0xFF if qw == (w - 1) and qh == (h - 1): return qc for ddir in direction: dw = ddir[0] + qw dh = ddir[1] + qh if dw >= w or dh >= h or dw < 0 or dh < 0 or v[dh][dw][qh][qw][qh2][qw2]: continue if flag: v[dh][dw][qh][qw][qh2][qw2] = True if (e[dh][dw] != e[qh][qw]) and (e[dh][dw] != e[qh2][qw2]) and (e[qh][qw] != e[qh2][qw2]): if (e[dh][dw] > e[qh][qw] and e[qh][qw] < e[qh2][qw2]) or (e[dh][dw] < e[qh][qw] and e[qh][qw] > e[qh2][qw2]): q.append((1 << 48) + ((qc + 1) << 32) + (qw << 24) + (qh << 16) + (dw << 8) + dh) else: q.append((1 << 48) + ((qc + 1) << 32) + (qw << 24) + (qh << 16) + (dw << 8) + dh) return -1 print(solve())