from heapq import * # 入力 h,w = map(int,input().split()) A = [list(map(int,input().split())) for _ in range(h)] if((2<=h<=10**3)==False): print(-1) if((2<=w<=10**3)==False): print(-1) M = set() for i in range(h): for j in range(w): if((1<=A[i][j]<=10**9)==False): print(-1) M.add(A[i][j]) if(len(M) != h*w): print(-1) # BFSで使うqueを用意 queA = [(A[0][0], 0, 0)] heapify(queA) colorA = [[-1 for j in range(w)]for i in range(h)] usedA = [[-1 for j in range(w)]for i in range(h)] usedA[0][0] = 0 queB = [(A[-1][-1], h-1, w-1)] heapify(queB) colorB = [[-1 for j in range(w)]for i in range(h)] usedB = [[-1 for j in range(w)]for i in range(h)] usedB[-1][-1] = 1 # マス(i,j)と隣接している頂点リストを返す def nextV(i,j): V = [] # 上 if((i == 0) == False): V.append((A[i-1][j], i-1, j)) # 下 if((i == h-1) == False): V.append((A[i+1][j], i+1, j)) # 左 if((j == 0) == False): V.append((A[i][j-1], i, j-1)) # 右 if((j == w-1) == False): V.append((A[i][j+1], i, j+1)) return V # 色1を広げる def f(): v = heappop(queA) colorA[v[1]][v[2]] = 1 # 色1と色0が隣接したら出力 for nv in nextV(v[1], v[2]): if(colorB[nv[1]][nv[2]] == 0): print(i-1) exit() # 次の頂点をみる for nv in nextV(v[1], v[2]): if(usedA[nv[1]][nv[2]] == -1): heappush(queA, nv) usedA[nv[1]][nv[2]] = 0 # 色0を広げる def g(): v = heappop(queB) colorB[v[1]][v[2]] = 0 # 色1と色0が隣接したら出力 for nv in nextV(v[1], v[2]): if(colorA[nv[1]][nv[2]] == 1): print(i-1) exit() # 次の頂点をみる for nv in nextV(v[1], v[2]): if(usedB[nv[1]][nv[2]] == -1): heappush(queB, nv) usedB[nv[1]][nv[2]] = 0 # 愚直にシミュレーション for i in range(h*w): if(i%2 == 0): f() elif(i%2 == 1): g()