import sys, time, random from collections import deque, Counter, defaultdict input = lambda: sys.stdin.readline().rstrip() ii = lambda: int(input()) mi = lambda: map(int, input().split()) li = lambda: list(mi()) inf = 2 ** 61 - 1 mod = 998244353 import heapq class Heap(): def __init__(self, maxi = False): self.sum = 0 self.al = [] self.maxi = maxi self.len = 0 def __len__(self): return len(self.al) def add(self, x): if self.maxi: heapq.heappush(self.al, -x) else: heapq.heappush(self.al, x) def pop(self): if self.maxi: now = heapq.heappop(self.al) return -now else: now = heapq.heappop(self.al) return now def top(self): now = self.pop() self.add(now) return now h, w = mi() a = [li() for _ in range(h)] zero = Heap() one = Heap() color = [[-1] * w for _ in range(h)] zero.add((a[0][0], 0, 0)) one.add((a[h - 1][w - 1], h - 1, w - 1)) i = 0 while True: if i % 2 == 0: now, x, y = zero.pop() else: now, x, y = one.pop() if color[x][y] != -1: continue color[x][y] = i % 2 f = True for tox, toy in [(1, 0), (-1, 0), (0, 1), (0, -1)]: nx, ny = x + tox, y + toy if 0 <= nx < h and 0 <= ny < w and color[nx][ny] == -1: if i % 2 == 0: zero.add((a[nx][ny], nx, ny)) else: one.add((a[nx][ny], nx, ny)) elif 0 <= nx < h and 0 <= ny < w and color[nx][ny] == 1 - color[x][y] and color[nx][ny] != -1: f = False break i += 1 if not f: break print(i - 2)