""" 愚直 """ import sys from collections import deque import itertools import heapq def exist(A): q = [] #print (A) for i in range(H): for j in range(W): if A[i][j] != None and A[i][j] >= 0: heapq.heappush( q , (A[i][j],i,j) ) if A[i][j] == None: A[i][j] = float("inf") while q: cost,i,j = heapq.heappop(q) if cost != A[i][j]: continue for x,y in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)): if 0 <= x < H and 0 <= y < W: if A[x][y] > A[i][j] + 1: A[x][y] = A[i][j] + 1 heapq.heappush( q, (A[x][y],x,y) ) if x==0 or x==H-1 or y==0 or y==W-1: return False return True import sys mod = 998244353 H,W = map(int,input().split()) assert 3 <= H <= 1000 assert 3 <= W <= 1000 A = [[None] * W for i in range(H)] # input A[0] = list(map(int,input().split())) for i in range(1,H-1): A[i][0],A[i][-1] = map(int,input().split()) A[-1] = list(map(int,input().split())) for i in range(H): for j in range(W): if A[i][j] != None: assert 1 <= A[i][j] <= 2000 flag = True for i in range(H): for j in range(W): if A[i][j] == None: continue for i2,j2 in ( (i+1,j),(i,j+1) ): if i2 < H and j2 < W and A[i2][j2] != None: if abs(A[i][j] - A[i2][j2]) > 1: flag = False if not flag: print (-1) sys.exit() yoko = [] tate = [] last = False for i in range(H): diff = abs(A[i][0] - A[i][-1]) if diff > W-1: yoko.append(i) for j in range(W): diff = abs(A[0][j] - A[-1][j]) if diff > H-1: tate.append(j) if tate: A = [[ A[i][j] for i in range(H) ] for j in range(W)] H,W = W,H yoko,tate = tate,yoko ans = 0 for bits in range((W-2)**len(yoko)): js = [] for mmm in range(len(yoko)): js.append( bits % (W-2) + 1 ) bits //= W-2 B = [[ A[i][j] for j in range(W) ] for i in range(H)] for i,j in zip(yoko,js): B[i][j] = -1 if exist(B): ans += 1 print (ans)