from heapq import heappop, heappush H, W = map(int, input().split()) A = [list(map(int, input().split())) for _ in range(H)] di, dj = [1, 0, -1, 0], [0, 1, 0, -1] hq1 = [] hq2 = [] C = [[-1] * W for _ in range(H)] C[0][0] = 0 C[-1][-1] = 1 add1 = [[False] * W for _ in range(H)] add2 = [[False] * W for _ in range(H)] for d in range(4): ni, nj = di[d], dj[d] if 0 <= ni < H and 0 <= nj < W: add1[ni][nj] = True heappush(hq1, (A[ni][nj], ni, nj)) for d in range(4): ni, nj = H - 1 + di[d], W - 1 + dj[d] if 0 <= ni < H and 0 <= nj < W: add2[ni][nj] = True heappush(hq2, (A[ni][nj], ni, nj)) ans = 1 while hq1 and hq2: if ans & 1: v, i, j = heappop(hq1) C[i][j] = 0 for d in range(4): ni, nj = i + di[d], j + dj[d] if 0 <= ni < H and 0 <= nj < W and C[ni][nj] != -1 and C[ni][nj] != C[i][j]: print(ans) exit() if 0 <= ni < H and 0 <= nj < W and C[ni][nj] == -1 and not add1[ni][nj]: add1[ni][nj] = True heappush(hq1, (A[ni][nj], ni, nj)) else: v, i, j = heappop(hq2) C[i][j] = 1 for d in range(4): ni, nj = i + di[d], j + dj[d] if 0 <= ni < H and 0 <= nj < W and C[ni][nj] != -1 and C[ni][nj] != C[i][j]: print(ans) exit() if 0 <= ni < H and 0 <= nj < W and C[ni][nj] == -1 and not add2[ni][nj]: add2[ni][nj] = True heappush(hq2, (A[ni][nj], ni, nj)) ans += 1 assert 0