In this problem, a $n \times m$ rectangular matrix $a$ is called increasing if, for each row of $i$, when go from left to right, the values strictly increase (that is, $a_{i,1}<a_{i,2}<\dots<a_{i,m}$) and for each column $j$, when go from top to bottom, the values strictly increase (that is, $a_{1,j}<a_{2,j}<\dots<a_{n,j}$).

In a given matrix of non-negative integers, it is necessary to replace each value of $0$ with some positive integer so that the resulting matrix is increasing and the sum of its elements is maximum, or find that it is impossible.

It is guaranteed that in a given value matrix all values of $0$ are contained only in internal cells (that is, not in the first or last row and not in the first or last column).


-----Input-----

The first line contains integers $n$ and $m$ ($3 \le n, m \le 500$) — the number of rows and columns in the given matrix $a$.

The following lines contain $m$ each of non-negative integers — the values in the corresponding row of the given matrix: $a_{i,1}, a_{i,2}, \dots, a_{i,m}$ ($0 \le a_{i,j} \le 8000$).

It is guaranteed that for all $a_{i,j}=0$, $1 < i < n$ and $1 < j < m$ are true.


-----Output-----

If it is possible to replace all zeros with positive numbers so that the matrix is increasing, print the maximum possible sum of matrix elements. Otherwise, print -1.


-----Examples-----
Input
4 5
1 3 5 6 7
3 0 7 0 9
5 0 0 0 10
8 9 10 11 12

Output
144

Input
3 3
1 2 3
2 0 4
4 5 6

Output
30

Input
3 3
1 2 3
3 0 4
4 5 6

Output
-1

Input
3 3
1 2 3
2 3 4
3 4 2

Output
-1



-----Note-----

In the first example, the resulting matrix is as follows: 

1 3 5 6 7

3 6 7 8 9

5 7 8 9 10

8 9 10 11 12



In the second example, the value $3$ must be put in the middle cell.

In the third example, the desired resultant matrix does not exist.

Difficulty: EASY

Solutions:
(n, m) = map(int, input().split())
a = [[0 for i in range(m)] for j in range(n)]
sum1 = 0
fg = 0
for i in range(n):
	a[i] = list(map(int, input().split()))
for i in range(n - 1, 0, -1):
	for j in range(m - 1, 0, -1):
		if a[i][j] == 0:
			a[i][j] = min(a[i + 1][j], a[i][j + 1]) - 1
		if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]:
			fg = 1
			break
if fg != 1:
	for i in range(n):
		for j in range(m):
			sum1 += a[i][j]
	print(sum1)
else:
	print(-1)


import sys
ii = lambda : sys.stdin.readline().strip()
idata = lambda : [int(x) for x in ii().split()]

def solve():
	(n, m) = idata()
	posle_progulki_po_strokam = []
	matrix = []
	summ = 0
	flag = True
	for i in range(n):
		s = idata()
		matrix += [s[:]]
		d = 0
		q = 0
		for j in range(m):
			if s[j] and d:
				if s[j] - q <= d:
					flag = False
				for w in range(d):
					s[j - w - 1] = s[j - w] - 1
				d = 0
				q = s[j]
			elif s[j]:
				if q >= s[j]:
					flag = False
				q = s[j]
			else:
				d += 1
		posle_progulki_po_strokam += [s[:]]
	for i in range(m):
		s = []
		for k in range(n):
			s += [posle_progulki_po_strokam[k][i]]
		s1 = []
		for k in range(n):
			s1 += [matrix[k][i]]
		d = 0
		q = 0
		for j in range(n):
			if s1[j] and d:
				if s1[j] - q <= d:
					flag = False
				for w in range(d):
					s[j - w - 1] = min(s[j - w] - 1, s[j - w - 1])
				if j - d != 0 and s[j - d] <= s[j - d - 1]:
					flag = False
				d = 0
				q = s1[j]
			elif s1[j]:
				if q >= s1[j]:
					flag = False
				q = s1[j]
			else:
				d += 1
		summ += sum(s)
	if not flag:
		print(-1)
		return
	print(summ)
	return
solve()


from math import inf

def is_increasing_matrix(matrix, r, c):
	for i in range(r):
		for j in range(c):
			top = -1 if i == 0 else matrix[i - 1][j]
			bottom = inf if i == r - 1 else matrix[i + 1][j]
			left = -1 if j == 0 else matrix[i][j - 1]
			right = inf if j == c - 1 else matrix[i][j + 1]
			if not (left < matrix[i][j] < right and top < matrix[i][j] < bottom):
				return False
	return True

def main():
	(r, c) = map(int, input().split())
	matrix = []
	for i in range(r):
		matrix.append(list(map(int, input().split())))
	changed = False
	for i in range(r - 2, 0, -1):
		for j in range(c - 2, 0, -1):
			upper_margin = matrix[i][j + 1] + matrix[i + 1][j] if 0 in [matrix[i][j + 1], matrix[i + 1][j]] else min(matrix[i][j + 1], matrix[i + 1][j])
			lower_margin = max(matrix[i][j - 1], matrix[i - 1][j])
			if lower_margin >= upper_margin - 1:
				print(-1)
				return
			if matrix[i][j] == 0:
				matrix[i][j] = upper_margin - 1
				changed = True
	if not changed:
		if not is_increasing_matrix(matrix, r, c):
			print(-1)
			return
	print(sum([sum(row) for row in matrix]))
main()


(n, m) = map(int, input().split())
g = [[]] * n
for a in range(n):
	g[a] = input().split()
	g[a] = [int(x) for x in g[a]]
total = 0
for c in range(n - 1, 0 - 1, -1):
	for d in range(m - 1, 0 - 1, -1):
		if g[c][d] == 0:
			g[c][d] = min(g[c + 1][d], g[c][d + 1]) - 1
		total += g[c][d]
for a in range(0, n - 1):
	for b in range(0, m):
		if g[a][b] >= g[a + 1][b]:
			total = -1
for a in range(0, n):
	for b in range(0, m - 1):
		if g[a][b] >= g[a][b + 1]:
			total = -1
print(total)


(n, m) = map(int, input().split())
matrix = []
for _ in range(n):
	matrix.append([int(i) for i in input().split()] + [float('inf')])
matrix.append([float('inf') for _ in range(m + 1)])
n -= 1
m -= 1
total_sum = 0
flag = 0
for row in range(n, -1, -1):
	for column in range(m, -1, -1):
		if matrix[row][column] != 0:
			if not (matrix[row][column] < matrix[row + 1][column] and matrix[row][column] < matrix[row][column + 1]):
				flag = 1
				break
		else:
			matrix[row][column] = min(matrix[row + 1][column], matrix[row][column + 1]) - 1
		total_sum += matrix[row][column]
	if flag == 1:
		break
print(-1 if flag == 1 else total_sum)


(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
tr = True
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if a[i][j] == 0:
			if i + 1 < n:
				ans = a[i + 1][j] - 1
				if i - 1 > -1:
					ans = max(ans, a[i - 1][j] + 1)
			if j + 1 < m:
				ans = min(ans, a[i][j + 1] - 1)
				if j - 1 > -1:
					ans = max(ans, a[i][j - 1] + 1)
			a[i][j] = ans
		if i + 1 < n and (not a[i + 1][j] > a[i][j]):
			tr = False
			break
		if i - 1 > -1 and (not a[i - 1][j] < a[i][j]):
			tr = False
			break
		if j + 1 < m and (not a[i][j + 1] > a[i][j]):
			tr = False
			break
		if j - 1 > -1 and (not a[i][j - 1] < a[i][j]):
			tr = False
			break
if tr:
	ans = 0
	for i in a:
		ans += sum(i)
	print(ans)
else:
	print('-1')


import os
import sys
from io import BytesIO, IOBase

def main():
	line = input().split()
	(n, m) = (int(line[0]), int(line[1]))
	arr = []
	pos = []
	for i in range(n):
		line = input().split()
		x = []
		for j in range(m):
			x.append(int(line[j]))
		arr.append(x)
	for i in range(1, n):
		for j in range(1, m):
			if arr[i][j] == 0:
				pos.append([i, j])
				arr[i][j] = max(arr[i][j - 1], arr[i - 1][j])
	pos.reverse()
	for (i, j) in pos:
		arr[i][j] = min(arr[i + 1][j], arr[i][j + 1]) - 1
	flag1 = 0
	flag2 = 0
	for i in range(n):
		val = arr[i][0]
		for x in range(1, m):
			if arr[i][x] > val:
				val = arr[i][x]
			else:
				flag1 = 1
				break
		if flag1 == 1:
			break
	for i in range(m):
		val = arr[0][i]
		for j in range(1, n):
			if arr[j][i] > val:
				val = arr[j][i]
			else:
				flag2 = 1
				break
		if flag2 == 1:
			break
	if flag1 == 1 or flag2 == 1:
		print('-1')
	else:
		summ = 0
		for i in arr:
			summ += sum(i)
		print(summ)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
sum_ = 0
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if 0 < i < n - 1 and 0 < j < m - 1:
			if a[i][j] == 0:
				a[i][j] = min(a[i][j + 1] - 1, a[i + 1][j] - 1)
		if i > 0 and a[i - 1][j] >= a[i][j]:
			print(-1)
			exit(0)
		if j > 0 and a[i][j - 1] >= a[i][j]:
			print(-1)
			exit(0)
		sum_ += a[i][j]
print(sum_)


import sys
(n, m) = map(int, input().split())
matrix = []
for i in range(n):
	matrix.append(list(map(int, input().split())))
for i in range(n - 2, 0, -1):
	for j in range(m - 2, 0, -1):
		if matrix[i][j] == 0:
			d1 = matrix[i + 1][j] - matrix[i - 1][j]
			d2 = matrix[i][j + 1] - matrix[i][j - 1]
			if d1 > 1 and d2 > 1:
				matrix[i][j] = min(matrix[i + 1][j], matrix[i][j + 1]) - 1
			elif d1 > 0 and d2 > 0:
				continue
			else:
				print(-1)
				sys.exit()
ans = 0
for i in range(n):
	prev = matrix[i][0]
	ans += prev
	for j in range(m - 1):
		if prev < matrix[i][j + 1]:
			prev = matrix[i][j + 1]
			ans += prev
		else:
			print(-1)
			sys.exit()
ans = 0
for j in range(m):
	prev = matrix[0][j]
	ans += prev
	for i in range(n - 1):
		if prev < matrix[i + 1][j]:
			prev = matrix[i + 1][j]
			ans += prev
		else:
			print(-1)
			sys.exit()
print(ans)


import sys

def solution(n, m, a):
	if n == 0 or m == 0:
		print(-1)
		return
	res = 0
	for j in range(m - 1):
		if a[0][j] >= a[0][j + 1]:
			print(-1)
			return
		res += a[0][j]
		if a[n - 1][j] >= a[n - 1][j + 1]:
			print(-1)
			return
		res += a[n - 1][j]
	for i in range(n - 1):
		if a[i][0] >= a[i + 1][0]:
			print(-1)
			return
		res += a[i][0]
		if a[i][m - 1] >= a[i + 1][m - 1]:
			print(-1)
			return
		res += a[i][m - 1]
	res -= a[0][0]
	res += a[n - 1][m - 1]
	for i in range(n - 2, 0, -1):
		for j in range(m - 2, 0, -1):
			upper_bound = min(a[i + 1][j], a[i][j + 1])
			if a[i][j] == 0:
				a[i][j] = upper_bound - 1
			elif a[i][j] >= upper_bound:
				print(-1)
				return
			res += a[i][j]
			lower_bound = max(a[i - 1][j], a[i][j - 1])
			if a[i][j] <= lower_bound:
				print(-1)
				return
	print(res)
(n, m) = sys.stdin.readline().split()
n = int(n)
m = int(m)
a = []
for i in range(n):
	lst = sys.stdin.readline().split()
	for j in range(len(lst)):
		lst[j] = int(lst[j])
	a.append(lst)
solution(n, m, a)


(n, m) = map(int, input().split(' '))
matrix = []
for i in range(n):
	row = [int(x) for x in input().split(' ')]
	matrix.append(row)

def determine(matrix, n, m):
	sum_max = matrix[n - 1][m - 1]
	for j in range(m - 2, -1, -1):
		if matrix[n - 1][j] < matrix[n - 1][j + 1]:
			if matrix[n - 1][j] == 0:
				matrix[n - 1][j] = matrix[n - 1][j + 1] - 1
			sum_max += matrix[n - 1][j]
		else:
			return -1
	for i in range(n - 2, -1, -1):
		if matrix[i][m - 1] < matrix[i + 1][m - 1]:
			if matrix[i][m - 1] == 0:
				matrix[i][m - 1] = matrix[i + 1][m - 1] - 1
			sum_max += matrix[i][m - 1]
		else:
			return -1
	for i in range(n - 2, -1, -1):
		for j in range(m - 2, -1, -1):
			if matrix[i][j] < min(matrix[i + 1][j], matrix[i][j + 1]):
				if matrix[i][j] == 0:
					matrix[i][j] = min(matrix[i + 1][j], matrix[i][j + 1]) - 1
				sum_max += matrix[i][j]
			else:
				return -1
	return sum_max
sum_max = determine(matrix, n, m)
print(sum_max)


(n, m) = map(int, input().split())
mat = [0 for i in range(n)]
for i in range(n):
	lst = list(map(int, input().split()))
	mat[i] = lst
i = n - 1
flag = 0
while i >= 1:
	j = m - 1
	while j >= 1:
		if mat[i][j] == 0:
			mat[i][j] = min(mat[i + 1][j], mat[i][j + 1]) - 1
		if mat[i][j] <= mat[i - 1][j] or mat[i][j] <= mat[i][j - 1]:
			flag = 1
			break
		j -= 1
	if flag:
		break
	i -= 1
if flag:
	print('-1')
else:
	ans = 0
	for i in range(n):
		for j in range(m):
			ans += mat[i][j]
	print(ans)


(a, b) = map(int, input().split())
z = []
for i in range(a):
	z += [[*map(int, input().split())]]
for i in range(a - 2, 0, -1):
	for j in range(b - 2, 0, -1):
		if z[i][j] == 0:
			if z[i][j + 1] - z[i][j - 1] == 1 or z[i + 1][j] - z[i - 1][j] == 1:
				exit(print(-1))
			z[i][j] = min(z[i][j + 1] - 1, z[i + 1][j] - 1)
for i in range(a):
	for j in range(b - 1):
		if z[i][j] >= z[i][j + 1]:
			exit(print(-1))
for j in range(b):
	for i in range(a - 1):
		if z[i][j] >= z[i + 1][j]:
			exit(print(-1))
print(sum((z[i][j] for j in range(b) for i in range(a))))


(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]

def go():
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if not a[i][j]:
				a[i][j] = min(a[i + 1][j], a[i][j + 1]) - 1
			if i + 1 < n and a[i][j] >= a[i + 1][j] or (j + 1 < m and a[i][j] >= a[i][j + 1]):
				print(-1)
				return
	s = 0
	for v in a:
		s += sum(v)
	print(s)
go()


(n, m) = map(int, input().split())
mat = []
summ = 0
flag = 0
for i in range(n):
	mat.append(list(map(int, input().split())))
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if mat[i][j] == 0:
			if mat[i + 1][j] - mat[i - 1][j] >= 2 and mat[i][j + 1] - mat[i][j - 1] >= 2:
				if mat[i][j + 1] <= mat[i + 1][j]:
					mat[i][j] = mat[i][j + 1] - 1
				elif mat[i][j + 1] > mat[i + 1][j]:
					mat[i][j] = mat[i + 1][j] - 1
				if mat[i][j] >= mat[i + 1][j] or mat[i][j] >= mat[i][j + 1]:
					flag = 1
				if mat[i][j] >= mat[i + 1][j] or mat[i][j] >= mat[i][j + 1]:
					flag = 1
			else:
				flag = 1
for i in range(0, n):
	for j in range(0, m - 1):
		if mat[i][j] >= mat[i][j + 1]:
			flag = 1
			break
for j in range(m):
	for i in range(n - 1):
		if mat[i][j] >= mat[i + 1][j]:
			flag = 1
			break
for i in mat:
	summ += sum(i)
if flag == 0:
	print(summ)
else:
	print(-1)


(n, m) = list(map(int, input().split()))
a = []
s = 0
t = 0
for i in range(n):
	b = list(map(int, input().split()))
	a.append(b)
	s += sum(b)
for j in range(n - 1):
	for k in range(m - 1):
		if a[n - j - 1][m - k - 1] == 0:
			a[n - j - 1][m - k - 1] = min(a[n - j][m - k - 1], a[n - j - 1][m - k]) - 1
			s += min(a[n - j][m - k - 1], a[n - j - 1][m - k]) - 1
		if a[n - j - 2][m - k - 1] != 0 and a[n - j - 2][m - k - 1] >= a[n - j - 1][m - k - 1] or (a[n - j - 1][m - k - 2] != 0 and a[n - j - 1][m - k - 2] >= a[n - j - 1][m - k - 1]):
			t = 1
			break
	if t == 1:
		break
if t == 1:
	print('-1')
else:
	print(s)


(n, m) = list(map(int, input().split()))
l = []
for w in range(n):
	l.append(list(map(int, input().split())))
s = 0
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if l[i][j] == 0:
			l1 = min(l[i + 1][j] - 1, l[i][j + 1] - 1)
			l[i][j] = l1
		s += l[i][j]
for i in range(n):
	for j in range(m - 1):
		if l[i][j] >= l[i][j + 1]:
			print(-1)
			exit()
for i in range(n - 1):
	for j in range(m):
		if l[i][j] >= l[i + 1][j]:
			print(-1)
			exit()
print(s)


def solve():
	(n, m) = list(map(int, input().split(' ')))
	arr = []
	for i in range(n):
		arr.append(list(map(int, input().split(' '))))
	total = 0
	for row_index in range(n - 1, -1, -1):
		col_index = m - 1
		while col_index > 0:
			if arr[row_index][col_index] == 0:
				arr[row_index][col_index] = min(arr[row_index + 1][col_index], arr[row_index][col_index + 1]) - 1
			if arr[row_index][col_index] <= arr[row_index][col_index - 1]:
				print('-1')
				return
			col_index -= 1
		total += sum(arr[row_index])
	for col in range(m - 1, -1, -1):
		for row in range(n - 1, 0, -1):
			if arr[row][col] <= arr[row - 1][col]:
				print('-1')
				return
	print(total)
solve()


def main():
	(n, m) = map(int, input().split())
	l = list((list(map(int, input().split()))[::-1] for _ in range(n)))[::-1]
	for (r0, r1) in zip(l, l[1:-1]):
		for (i, a) in enumerate(r1[1:-1], 1):
			if not a:
				r1[i] = min(r1[i - 1], r0[i]) - 1
	print(sum(map(sum, l)) if all((r1[i - 1] > a < r0[i] for (r0, r1) in zip(l, l[1:]) for (i, a) in enumerate(r1[1:], 1))) and all((a < b for (a, b) in zip(l[0][1:], l[0]))) and all((r1[0] < r0[0] for (r0, r1) in zip(l, l[1:]))) else -1)
main()


(n, m) = map(int, input().split())
mat = []
sum = 0
for _ in range(n):
	row = list(map(int, input().split()))
	mat.append(row)
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if mat[i][j] == 0:
			mat[i][j] = min(mat[i + 1][j], mat[i][j + 1]) - 1
		sum += mat[i][j]
for i in range(n):
	for j in range(m - 1):
		if mat[i][j] >= mat[i][j + 1]:
			print(-1)
			exit()
for i in range(n - 1):
	for j in range(m):
		if mat[i][j] >= mat[i + 1][j]:
			print(-1)
			exit()
print(sum)


(r, c) = map(int, input().split())
s = [list(map(int, input().split())) for _ in range(r)]
re = 0
for i in range(r - 1, -1, -1):
	for j in range(c - 1, -1, -1):
		if 0 < i < r - 1 and 0 < j < c - 1:
			if s[i][j] == 0:
				s[i][j] = min(s[i + 1][j], s[i][j + 1]) - 1
			if s[i - 1][j] > 0 and s[i - 1][j] >= s[i][j] or (s[i][j - 1] > 0 and s[i][j - 1] >= s[i][j]):
				print(-1)
				return
		if i < r - 1 and j < c - 1:
			if s[i][j] >= s[i + 1][j] or s[i][j] >= s[i][j + 1]:
				print(-1)
				return
		if i < r - 1 and j == c - 1:
			if s[i][j] >= s[i + 1][j]:
				print(-1)
				return
		if i == r - 1 and j < c - 1:
			if s[i][j] >= s[i][j + 1]:
				print(-1)
				return
		re += s[i][j]
print(re)


(n, m) = map(int, input().split())
arr = []
for _ in range(n):
	arr.append(list(map(int, input().split())))
ans = 0
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if arr[i][j] == 0:
			if i < n - 1 and j < m - 1:
				arr[i][j] = min(arr[i + 1][j], arr[i][j + 1]) - 1
			elif j < m - 1:
				arr[i][j] = arr[i][j + 1] - 1
			else:
				arr[i][j] = arr[i + 1][j] - 1
		ans += arr[i][j]
flag = True
for i in range(n):
	for j in range(m):
		if i < n - 1 and j < m - 1:
			if arr[i][j] >= arr[i][j + 1] or arr[i][j] >= arr[i + 1][j] or arr[i][j] >= arr[i + 1][j + 1]:
				flag = False
				break
		if i < n - 1:
			if arr[i][j] >= arr[i + 1][j]:
				flag = False
				break
		if j < m - 1:
			if arr[i][j] >= arr[i][j + 1]:
				flag = False
				break
	if flag:
		pass
	else:
		break
if flag:
	print(ans)
else:
	print(-1)


def ii():
	return int(input())

def ss():
	return [x for x in input()]

def si():
	return [int(x) for x in input().split()]

def mi():
	return map(int, input().split())
(a, b) = mi()
s = []
ans = 0
key = True
for i in range(a):
	i = si()
	s.append(i)
	ans += sum(i)
for i in range(a - 1):
	if not (s[i][0] < s[i + 1][0] and s[i][-1] < s[i + 1][-1]):
		ans = -1
		key = False
		break
for i in range(b - 1):
	if not (s[0][i] < s[0][i + 1] and s[-1][i] < s[-1][i + 1]):
		ans = -1
		key = False
		break
for i in range(a - 2, 0, -1):
	if not key:
		break
	for x in range(b - 2, 0, -1):
		if s[i][x] < s[i + 1][x] and s[i][x] < s[i][x + 1] and (min(s[i + 1][x], s[i][x + 1]) - max(s[i - 1][x], s[i][x - 1]) > 1):
			if s[i][x] == 0:
				s[i][x] = min(s[i + 1][x], s[i][x + 1]) - 1
				ans += s[i][x]
		else:
			ans = -1
			key = False
			break
print(ans)


(Positions, Matrix, X) = ([], [], list(map(int, input().split())))
for i in range(X[0]):
	Temp = list(map(int, input().split()))
	for j in range(X[1]):
		if Temp[j] == 0:
			Positions.append([i, j])
	Matrix.append(Temp)
(Count, Positions) = (0, list(reversed(Positions)))
for i in Positions:
	Temp = min(Matrix[i[0]][i[1] + 1], Matrix[i[0] + 1][i[1]]) - 1
	if Temp > max(Matrix[i[0] - 1][i[1]], Matrix[i[0]][i[1] - 1]):
		Count += Temp
		Matrix[i[0]][i[1]] = Temp
	else:
		print(-1)
		exit()
for i in range(X[0]):
	for j in range(1, X[1]):
		if Matrix[i][j] <= Matrix[i][j - 1]:
			print(-1)
			exit()
for i in range(X[1]):
	for j in range(1, X[0]):
		if Matrix[j][i] <= Matrix[j - 1][i]:
			print(-1)
			exit()
print(sum((sum(i) for i in Matrix)))


import sys
(n, m) = map(int, input().split())
M = []
for i in range(n):
	M += [list(map(int, input().split()))]
S = M[-1][-1]
for j in range(n - 2, -1, -1):
	if M[j][-1] >= M[j + 1][-1]:
		print(-1)
		return
	if M[j][-1] == 0:
		M[j][-1] = M[j - 1][-1] - 1
	S += M[j][-1]
for j in range(m - 2, -1, -1):
	if M[-1][j] >= M[-1][j + 1]:
		print(-1)
		return
	if M[-1][j] == 0:
		M[-1][j] = M[-1][j - 1] - 1
	S += M[-1][j]
for k in range(m - 2, -1, -1):
	for p in range(n - 2, -1, -1):
		if M[p][k] >= min(M[p + 1][k], M[p][k + 1]):
			print(-1)
			return
		if M[p][k] == 0:
			M[p][k] = min(M[p + 1][k], M[p][k + 1]) - 1
		S += M[p][k]
print(S)


(n, m) = map(int, input().split())
l = [list(map(int, input().split())) for _ in range(n)]
ans = 0
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if l[i][j] == 0:
			mr = l[i][j + 1] - 1
			mc = l[i + 1][j] - 1
			l[i][j] = min(mr, mc)
			ans += l[i][j]
		else:
			ans += l[i][j]
ch = 0
for i in range(n):
	dic = {}
	for j in range(m):
		if l[i][j] not in dic:
			dic[l[i][j]] = 1
			if j > 0:
				if l[i][j] <= l[i][j - 1]:
					ch = 1
					break
		else:
			ch = 1
			break
	if ch:
		break
if not ch:
	for j in range(m):
		dic = {}
		for i in range(n):
			if l[i][j] not in dic:
				dic[l[i][j]] = 1
				if i > 0:
					if l[i][j] <= l[i - 1][j]:
						ch = 1
						break
			else:
				ch = 1
				break
		if ch:
			break
if ch:
	print(-1)
else:
	print(ans)


(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
b = True
for i in range(n - 2, -1, -1):
	for j in range(m - 2, -1, -1):
		if a[i][j] == 0:
			a[i][j] = min(a[i + 1][j], a[i][j + 1]) - 1
for i in range(n):
	for j in range(m):
		if (i == n - 1 or a[i][j] < a[i + 1][j]) and (j == m - 1 or a[i][j] < a[i][j + 1]):
			continue
		b = False
if b:
	x = 0
	for i in range(n):
		x += sum(a[i])
	print(x)
else:
	print(-1)


def sum_matr(matr):
	for i in (0, n - 1):
		for j in range(m - 1):
			if matr[i][j] >= matr[i][j + 1]:
				return -1
	for j in (0, m - 1):
		for i in range(n - 1):
			if matr[i][j] >= matr[i + 1][j]:
				return -1
	for i in range(n - 2, 0, -1):
		for j in range(m - 2, 0, -1):
			if matr[i][j] == 0:
				c = min(matr[i][j + 1] - 1, matr[i + 1][j] - 1)
				if c <= matr[i][j - 1] or c <= matr[i - 1][j]:
					return -1
				else:
					matr[i][j] = c
			elif matr[i][j] >= matr[i + 1][j] or matr[i][j] >= matr[i + 1][j]:
				return -1
	s = 0
	for i in range(n):
		for j in range(m):
			s += matr[i][j]
	return s
(n, m) = [int(elem) for elem in input().split()]
matr = []
for i in range(n):
	matr.append([int(elem) for elem in input().split()])
print(sum_matr(matr))


import os
import sys
from io import BytesIO, IOBase
import math
from decimal import *
from collections import defaultdict
getcontext().prec = 25
MOD = pow(10, 9) + 7
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, m) = map(int, input().split(' '))
l = []
a = []
b = []
for i in range(n):
	x = list(map(int, input().split(' ')))
	l.append(x)
	a.append(x[0])
	b.append(x[-1])
ans = 1
t = sum(l[0]) + sum(l[-1])
if l[0] != sorted(l[0]) or l[-1] != sorted(l[-1]) or len(l[0]) != len(set(l[0])) or (len(l[-1]) != len(set(l[-1]))):
	ans = 0
if a != sorted(a) or b != sorted(b) or len(a) != len(set(a)) or (len(b) != len(set(b))):
	ans = 0
for i in range(n - 2, 0, -1):
	for j in range(m - 2, 0, -1):
		if l[i][j] == 0:
			l[i][j] = min(l[i + 1][j], l[i][j + 1]) - 1
	for j in range(m - 1):
		if l[i][j] >= l[i][j + 1]:
			ans = 0
			break
	t += sum(l[i])
if ans:
	print(t)
else:
	print(-1)


import sys
(n, m) = map(int, input().split())
a = [[*map(int, input().split())] for _ in range(n)]
try:
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if a[i][j] == 0:
				a[i][j] = min(a[i + 1][j], a[i][j + 1]) - 1
			if i + 1 < n:
				assert a[i][j] < a[i + 1][j]
			if j + 1 < m:
				assert a[i][j] < a[i][j + 1]
	print(sum(map(sum, a)))
except AssertionError:
	print(-1)


(n, m) = list(map(int, input().split()))
matrix = []
for _ in range(n):
	matrix.append(list(map(int, input().split())))
ans = 'yes'
total = 0
a = matrix.copy()
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if i + 1 < n and j + 1 < m:
			possible_max = min(a[i + 1][j], a[i][j + 1])
		elif i + 1 < n:
			possible_max = a[i + 1][j]
		elif j + 1 < m:
			possible_max = a[i][j + 1]
		else:
			total += a[i][j]
			continue
		if a[i][j] == 0:
			a[i][j] = possible_max - 1
			if a[i][j] <= 0:
				ans = 'no'
				break
		elif a[i][j] >= possible_max:
			ans = 'no'
			break
		total += a[i][j]
	if ans == 'no':
		break
if ans == 'yes':
	print(total)
else:
	print(-1)


n = input().split()
m = int(n[0])
n = int(n[1])
mat = []
for i in range(m):
	temp = list(map(int, input().split()))
	mat.append(temp)
for i in range(m - 1, 0, -1):
	for j in range(n - 1, 0, -1):
		if mat[i][j] == 0:
			mat[i][j] = min(mat[i][j + 1], mat[i + 1][j]) - 1
counter = 0
for i in range(m - 1):
	for j in range(n - 1):
		if mat[i + 1][j] <= mat[i][j] or mat[i][j + 1] <= mat[i][j]:
			counter = 1
			break
	if mat[m - 1][n - 1] <= mat[m - 2][n - 1] or mat[m - 1][n - 1] <= mat[m - 1][n - 2] or counter == 1:
		counter = 1
		break
if counter == 1:
	print(-1)
else:
	final = sum([sum(i) for i in mat])
	print(final)


(n, m) = [int(i) for i in input().split()]
a = [[int(j) for j in input().split()] for i in range(n)]
wa = 0
for y in range(n):
	if y != 0 and (a[y][0] <= a[y - 1][0] or a[y][m - 1] <= a[y - 1][m - 1]):
		wa = 1
for y in range(m):
	if y != 0 and (a[0][y] <= a[0][y - 1] or a[n - 1][y] <= a[n - 1][y - 1]):
		wa = 1
for x in range(n - 2):
	for y in range(m - 2):
		if a[n - x - 2][m - y - 2] == 0:
			a[n - x - 2][m - y - 2] = min(a[n - x - 2][m - y - 1], a[n - x - 1][m - y - 2]) - 1
		if a[n - x - 2][m - y - 2] <= max(a[n - x - 2][m - y - 3], a[n - x - 3][m - y - 2]):
			wa = 1
			break
	if wa == 1:
		break
if wa == 1:
	print(-1)
else:
	ans = 0
	for x in a:
		for y in x:
			ans += y
	print(ans)


def valid(grid, r, c):
	for i in range(r):
		for j in range(1, c):
			if grid[i][j] <= grid[i][j - 1]:
				return False
	for i in range(c):
		for j in range(1, r):
			if grid[j][i] <= grid[j - 1][i]:
				return False
	return True
(n, m) = map(int, input().split())
A = []
for i in range(n):
	a = list(map(int, input().split()))
	A.append(a)
for i in range(n - 2, 0, -1):
	for j in range(m - 2, 0, -1):
		if not A[i][j]:
			A[i][j] = min(A[i + 1][j], A[i][j + 1]) - 1
if valid(A, n, m):
	print(sum((A[i][j] for i in range(n) for j in range(m))))
else:
	print(-1)


def comp(A):
	for i in range(n - 2, -1, -1):
		for j in range(m - 2, -1, -1):
			if A[i + 1][j + 1] <= A[i][j + 1] or A[i + 1][j + 1] <= A[i + 1][j]:
				return -1
			if A[i][j] == 0:
				A[i][j] = min(A[i + 1][j] - 1, A[i][j + 1] - 1)
				if A[i][j] <= A[i - 1][j] or A[i][j] <= A[i][j - 1] or A[i][j] == 0:
					return -1
	return sum([sum(A[i]) for i in range(n)])
(n, m) = map(int, input().rstrip().split())
A = []
for i in range(n):
	A.append(list(map(int, input().rstrip().split())))
res = comp(A)
print(res)


(n, m) = map(int, input().split())
l = [list(map(int, input().split())) for _ in range(n)]
s = sum(l[0]) + sum(l[-1])
xf = 0
for i in range(m - 1):
	if l[0][i] >= l[0][i + 1] or l[-1][i] >= l[-1][i + 1]:
		xf = 1
		break
if xf == 1:
	print(-1)
else:
	for i in range(n - 2, 0, -1):
		s += l[i][0] + l[i][-1]
		for j in range(m - 2, 0, -1):
			if l[i][j] == 0:
				if l[i][j + 1] - l[i][j - 1] <= 1 or l[i + 1][j] - l[i - 1][j] <= 1:
					xf = 1
					break
				else:
					l[i][j] = min(l[i][j + 1] - 1, l[i + 1][j] - 1)
					s += l[i][j]
			elif l[i][j - 1] < l[i][j] < l[i][j + 1] and l[i - 1][j] < l[i][j] < l[i + 1][j]:
				s += l[i][j]
			else:
				xf = 1
				break
		if l[i][1] <= l[i][0] or l[i][-2] >= l[i][-1] or l[i][0] >= l[i + 1][0] or (l[i][0] <= l[i - 1][0]) or (l[i][-1] >= l[i + 1][-1]) or (l[i][-1] <= l[i - 1][-1]):
			xf = 1
		if xf == 1:
			print(-1)
			break
	else:
		print(s)


try:

	def check(a):
		for i in range(n):
			for j in range(1, m):
				if i == 0:
					if a[i][j] > a[i][j - 1]:
						pass
					else:
						raise Exception
				elif a[i][j] > max(a[i][j - 1], a[i - 1][j]):
					pass
				else:
					raise Exception
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split(' '))) for i in range(n)]
	for i in range(1, n - 1):
		for j in range(m - 2, 0, -1):
			if a[i][j] == 0:
				t = 0
				r = i
				while t == 0:
					t = a[r + 1][j]
					r += 1
				p = t - (r - i)
				p = min(p, a[i][j + 1] - 1)
				p1 = max(a[i][j - 1], a[i - 1][j])
				ans = 0
				for k in range(p, p1, -1):
					if k > p1:
						a[i][j] = k
						ans = 1
						break
				if ans == 0:
					raise Exception
	check(a)
	s = 0
	for i in a:
		s += sum(i)
	print(s)
except Exception:
	print('-1')


(n, m) = list(map(int, input().split()))
matrix = [0] * n
ok = 0
for q in range(0, n):
	row = list(map(int, input().split()))
	matrix[q] = row
zero = 0

def no_zeros(n, m):
	for g in range(0, n):
		for k in range(0, m - 1):
			if matrix[g][k] < matrix[g][k + 1]:
				pass
			else:
				return -1
	for l in range(0, m - 1):
		for m in range(0, n):
			if matrix[l][m] < matrix[l + 1][m]:
				pass
			else:
				return -1
	return find_sum(matrix)

def find_zero_value():
	for i in range(n - 1, 0, -1):
		for j in range(m - 1, 0, -1):
			if matrix[i][j] == 0:
				right = matrix[i][j + 1]
				down = matrix[i + 1][j]
				op_min = min([right, down])
				up = matrix[i - 1][j]
				left = matrix[i][j - 1]
				op_max = max([up, left])
				if op_min - 1 > op_max:
					matrix[i][j] = op_min - 1
				else:
					return -1
	return matrix

def find_sum(maz):
	su = 0
	for i in range(0, n):
		for j in range(0, m):
			su = su + matrix[i][j]
	return su
for i in range(0, n):
	for j in range(0, m):
		if matrix[i][j] == 0:
			zero = 1
			break
if zero == 0:
	print(no_zeros(n, m))
else:
	maz = find_zero_value()
	if maz == -1:
		print('-1')
	else:
		summ = find_sum(maz)
		print(summ)


import sys
(R, C) = map(int, sys.stdin.readline().rstrip().split())
table = [[0] * C for _ in range(R)]
for i in range(R):
	for (j, num) in enumerate(map(int, sys.stdin.readline().rstrip().split())):
		table[i][j] = num
for j in range(C - 2, 0, -1):
	for i in range(R - 2, 0, -1):
		if not table[i][j]:
			table[i][j] = min(table[i + 1][j], table[i][j + 1]) - 1

def valid(i, j, table=table):
	if j + 1 < C:
		if table[i][j] >= table[i][j + 1]:
			return False
	if i + 1 < R:
		if table[i][j] >= table[i + 1][j]:
			return False
	if j:
		if table[i][j] <= table[i][j - 1]:
			return False
	if i:
		if table[i][j] <= table[i - 1][j]:
			return False
	return True
ans = 0
for j in range(C - 1, -1, -1):
	for i in range(R - 1, -1, -1):
		if not valid(i, j):
			print(-1)
			exit(0)
		ans += table[i][j]
print(ans)


(n, m) = map(int, input().split())
mat = []
for i in range(n):
	mat.append(list(map(int, input().split())))
p = 0
for i in range(n - 2, 0, -1):
	for j in range(m - 2, 0, -1):
		if mat[i][j] == 0:
			mat[i][j] = min(mat[i + 1][j], mat[i][j + 1]) - 1
for i in range(1, n):
	for j in range(1, m):
		if i != n - 1 and j != m - 1 and (i != 0) and (j != 0):
			if mat[i][j] != 0 and mat[i + 1][j] != 0 and (mat[i][j + 1] != 0):
				if mat[i][j] >= mat[i][j + 1] or mat[i][j] >= mat[i + 1][j] or mat[i][j] == mat[i - 1][j] or (mat[i][j] == mat[i][j - 1]):
					p = 1
					break
for i in range(n - 1):
	if mat[i][0] >= mat[i + 1][0]:
		p = 1
for i in range(n - 1):
	if mat[i][m - 1] >= mat[i + 1][m - 1]:
		p = 1
for j in range(m - 1):
	if mat[0][j] >= mat[0][j + 1]:
		p = 1
for j in range(m - 1):
	if mat[n - 1][j] >= mat[n - 1][j + 1]:
		p = 1
if p == 1:
	print(-1)
else:
	s = 0
	for i in mat:
		s += sum(i)
	print(s)


y = [int(x) for x in input().split(' ')]
n_m = []
for i in range(y[0]):
	p = [int(x) for x in input().split(' ')]
	n_m.append(p)
sum = 0
h = True
for i in range(y[0] - 1, -1, -1):
	for j in range(y[1] - 1, -1, -1):
		if n_m[i][j] == 0:
			if n_m[i + 1][j] > n_m[i][j + 1]:
				n_m[i][j] = n_m[i][j + 1] - 1
			else:
				n_m[i][j] = n_m[i + 1][j] - 1
		try:
			if j == 0:
				pass
			elif i == 0:
				pass
			elif n_m[i][j] <= n_m[i][j - 1]:
				h = False
			elif n_m[i][j] <= n_m[i - 1][j]:
				h = False
		except:
			pass
		if h == False:
			print(-1)
			return
		sum += n_m[i][j]
print(sum)


import sys
(n, m) = list(map(int, sys.stdin.readline().strip().split()))
M = []
v = True
ans = 0
for i in range(0, n):
	M.append(list(map(int, sys.stdin.readline().strip().split())))
for i in range(0, n):
	r = n - i - 1
	for j in range(0, m):
		c = m - j - 1
		if M[r][c] == 0:
			M[r][c] = min(M[r + 1][c], M[r][c + 1]) - 1
		if r >= 1 and c >= 1:
			if M[r][c] <= M[r - 1][c] or M[r][c] <= M[r][c - 1]:
				v = False
	ans = ans + sum(M[r])
if v == True:
	print(ans)
else:
	print(-1)


(n, m) = map(int, input().split())
matr = [list(map(int, input().split())) for _ in range(n)]
for (i, st) in enumerate(matr):
	for (j, elem) in enumerate(st):
		if matr[~i][~j] == 0:
			matr[~i][~j] = min(matr[~i + 1][~j], matr[~i][~j + 1]) - 1
for (i, st) in enumerate(matr):
	for (j, elem) in enumerate(st):
		if i != 0 and j != 0:
			if matr[i][j] <= max(matr[i - 1][j], matr[i][j - 1]):
				print('-1')
				exit()
		elif i == 0 and j != 0:
			if matr[i][j] <= matr[i][j - 1]:
				print('-1')
				exit()
		elif i != 0 and j == 0:
			if matr[i][j] <= matr[i - 1][j]:
				print('-1')
				exit()
print(sum((sum(l) for l in matr)))


import sys
import math
get_string = lambda : sys.stdin.readline().strip()
get_int_list = lambda : list(map(int, sys.stdin.readline().strip().split()))
get_int = lambda : int(sys.stdin.readline())
pt = lambda x: sys.stdout.write(str(x) + '\n')
(n, m) = get_int_list()
matrix = []
for i in range(n):
	matrix.append(get_int_list())
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if matrix[i][j] == 0:
			matrix[i][j] = min(matrix[i + 1][j] - 1, matrix[i][j + 1] - 1)
flag = True
for i in range(1, n):
	for j in range(1, m):
		if matrix[i][j] <= matrix[i - 1][j] or matrix[i][j] <= matrix[i][j - 1]:
			flag = False
			break
	if not flag:
		break
if flag:
	s = 0
	for i in range(n):
		s += sum(matrix[i])
	print(s)
else:
	print(-1)


R = lambda : map(int, input().split())
(r, c) = R()
a = [[0] * (c + 2)]
for i in range(r):
	x = list(R())
	x = [0] + x + [x[-1] + 1]
	a.append(x)
a += [[a[-1][-1] + 1] * (c + 2)]
for i in range(r, 0, -1):
	for j in range(c, 0, -1):
		if a[i][j] == 0:
			a[i][j] = min(a[i][j + 1], a[i + 1][j]) - 1
		if a[i][j] <= max(a[i][j - 1], a[i - 1][j]) or a[i][j] >= min(a[i + 1][j], a[i][j + 1]):
			exit(print(-1))
print(sum([sum(a[i][1:c + 1]) for i in range(1, r + 1)]))


def is_valid(mtx):
	for i in range(len(mtx)):
		for j in range(len(mtx[i])):
			if mtx[i][j] != 0:
				if i - 1 >= 0 and mtx[i][j] <= mtx[i - 1][j] != 0:
					return False
				if j - 1 >= 0 and mtx[i][j] <= mtx[i][j - 1] != 0:
					return False
	return True

def get_sum(mtx):
	res = 0
	for i in range(len(mtx)):
		for j in range(len(mtx[i])):
			res += mtx[i][j]
	return res

def solve(mtx):
	if not is_valid(mtx):
		return -1
	update = 1
	for i in range(len(mtx) - 2, 0, -1):
		for j in range(len(mtx[i]) - 2, 0, -1):
			if mtx[i][j] == 0:
				updated = min(mtx[i][j + 1], mtx[i + 1][j]) - update
				if updated <= mtx[i][j - 1] or updated <= mtx[i - 1][j]:
					return -1
				mtx[i][j] = updated
			elif mtx[i][j] <= mtx[i][j - 1] or mtx[i][j] <= mtx[i - 1][j]:
				return -1
	return get_sum(mtx)
(n, m) = [int(x) for x in input().split()]
mat = []
for i in range(n):
	mat.append([int(x) for x in input().split()])
print(solve(mat))


(n, m) = map(int, input().split())
ma = [[int(i) for i in input().split()] for j in range(n)]
s = 0
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		s = s + ma[i][j]
		if ma[i][j] == 0:
			if min(ma[i + 1][j], ma[i][j + 1]) - 1 > max(ma[i - 1][j], ma[i][j - 1]):
				ma[i][j] = min(ma[i + 1][j], ma[i][j + 1]) - 1
				s = s + ma[i][j]
			else:
				print(-1)
				exit()
		elif i == n - 1 or (i + 1 < n and ma[i][j] < ma[i + 1][j]):
			if j == m - 1 or (j + 1 < m and ma[i][j] < ma[i][j + 1]):
				continue
			else:
				print(-1)
				exit()
		else:
			print(-1)
			exit()
print(s)


def check():
	global a
	ans = 0
	a = [[-1] * (len(a[0]) + 2)] + [[0] + a[i] + [float('inf')] for i in range(len(a))] + [[float('inf')] * (len(a[0]) + 2)]
	for row in range(1, len(a) - 1):
		for el in range(1, len(a[row]) - 1):
			if not (a[row - 1][el] < a[row][el] < a[row + 1][el] and a[row][el - 1] < a[row][el] < a[row][el + 1]):
				return -1
			ans += a[row][el]
	return ans
a = [[int(j) for j in input().split()] for i in range([int(i) for i in input().split()][0])]
for row in range(len(a) - 1, 0, -1):
	for el in range(len(a[row]) - 1, 0, -1):
		if a[row][el] == 0:
			a[row][el] = min(a[row + 1][el], a[row][el + 1]) - 1
print(check())


(n, m) = map(int, input().split())
mat = []
for i in range(n):
	mat.append(list(map(int, input().split())))
flag = 0
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if mat[i][j] == 0:
			mat[i][j] = min(mat[i + 1][j] - 1, mat[i][j + 1] - 1)
			if mat[i][j] <= mat[i - 1][j] or mat[i][j] <= mat[i][j - 1]:
				flag = 1
				break
		else:
			if i < n - 1 and mat[i][j] >= mat[i + 1][j] or (j < m - 1 and mat[i][j] >= mat[i][j + 1]):
				flag = 1
				break
			if i > 0 and mat[i][j] <= mat[i - 1][j] or (j > 0 and mat[i][j] <= mat[i][j - 1]):
				flag = 1
				break
	if flag:
		break
if flag:
	print(-1)
	exit()
s = 0
for i in range(n):
	for j in range(m):
		s += mat[i][j]
print(s)


def matrix(a, n, m):
	z = []
	for i in range(n):
		for j in range(m):
			if a[i][j] == 0:
				z.append((i, j))
	z.reverse()
	for i in z:
		a[i[0]][i[1]] = min(a[i[0] + 1][i[1]], a[i[0]][i[1] + 1]) - 1
	for i in range(n):
		for j in range(m - 1):
			if a[i][j] == a[i][j + 1]:
				return -1
			if a[i][j] > a[i][j + 1]:
				return -1
	for i in range(n - 1):
		for j in range(m):
			if a[i][j] > a[i + 1][j]:
				return -1
			if a[i][j] == a[i + 1][j]:
				return -1
	temp = 0
	for i in a:
		temp += sum(i)
	return temp
(n, m) = map(int, input().split())
a = []
for i in range(n):
	v = list(map(int, input().split()))
	a.append(v)
print(matrix(a, n, m))


(n, m) = map(int, input().split())
l = []
for i in range(n):
	l.append([int(s) for s in input().split()])
k = 0
for i in range(n - 1, 0, -1):
	for j in range(m - 1, 0, -1):
		if l[i - 1][j - 1] == 0:
			l[i - 1][j - 1] = min(l[i - 1][j], l[i][j - 1]) - 1
		if l[i - 1][j] >= l[i][j]:
			k = 1
			break
		if l[i][j - 1] >= l[i][j]:
			k = 1
			break
	if k == 1:
		break
if k == 1:
	print('-1')
else:
	sum1 = 0
	for i in range(n):
		for j in range(m):
			sum1 += l[i][j]
	print(sum1)


(n, m) = map(int, input().split())
mat = []
for i in range(n):
	mat.append(list(map(int, input().split())))
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if mat[i][j] == 0:
			mat[i][j] = min(mat[i + 1][j], mat[i][j + 1]) - 1
ans = 0
for i in range(n):
	for j in range(m):
		if i != 0 and j != 0 and (mat[i][j] <= mat[i - 1][j] or mat[i][j] <= mat[i][j - 1]):
			print(-1)
			exit()
		ans += mat[i][j]
print(ans)


import os
import sys
from io import BytesIO, IOBase

def main():
	(n, m) = r_array()
	mat = []
	for _ in range(n):
		mat.append(r_array())
	z = 0
	for i in range(n - 1, 0, -1):
		for j in range(m - 1, 0, -1):
			e = mat[i][j]
			if mat[i][j] == 0:
				k = min(mat[i + 1][j], mat[i][j + 1]) - 1
				mat[i][j] = k
				if k <= max(mat[i - 1][j], mat[i][j - 1]):
					z = 1
					break
			elif e <= max(mat[i - 1][j], mat[i][j - 1]):
				z = 1
				break
		if z == 1:
			break
	if z == 1:
		write(-1)
	else:
		write(sum([sum(i) for i in mat]))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def write(*args, end='\n'):
	for x in args:
		sys.stdout.write(str(x) + ' ')
	sys.stdout.write(end)

def r_array():
	return [int(x) for x in input().split()]

def r_int():
	return int(input())

def w_array(arr):
	for x in arr:
		write(x, end=' ')
	write()
main()


import sys
import string
from collections import Counter, defaultdict
from math import fsum, sqrt, gcd, ceil, factorial
from operator import add
inf = float('inf')
flush = lambda : sys.stdout.flush
comb = lambda x, y: factorial(x) // factorial(y) // factorial(x - y)
ip = lambda : input()
ii = lambda : int(input())
r = lambda : map(int, input().split())
rr = lambda : list(r())
(a, b) = r()
arr = [rr() for _ in range(a)]
for i in range(a - 2, 0, -1):
	for j in range(b - 2, 0, -1):
		if not arr[i][j]:
			arr[i][j] = min(arr[i + 1][j], arr[i][j + 1]) - 1
for i in range(1, a):
	if any((arr[i][j + 1] <= arr[i][j] for j in range(b - 1))):
		print(-1)
		exit()
for i in range(1, b):
	if any((arr[j + 1][i] <= arr[j][i] for j in range(a - 1))):
		print(-1)
		exit()
print(sum((sum(i) for i in arr)))


import sys

def ma():
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append([*map(int, sys.stdin.readline().split())])
	if a[n - 1][m - 1] <= a[n - 2][m - 1] or a[n - 1][m - 1] <= a[n - 1][m - 2]:
		return print(-1)
	for i in range(n - 2, 0, -1):
		for j in range(m - 2, 0, -1):
			if a[i][j] <= a[i + 1][j] or a[i][j] <= a[i][j + 1]:
				mi = min(a[i + 1][j], a[i][j + 1]) - 1
				if a[i][j] == 0:
					a[i][j] = min(a[i + 1][j], a[i][j + 1]) - 1
				if mi <= a[i - 1][j] or mi <= a[i][j - 1]:
					return print(-1)
			else:
				return print(-1)
	su = 0
	for i in range(n):
		su += sum(a[i])
	print(su)
ma()


import sys, copy
(n, m) = map(int, sys.stdin.readline().split())
arr = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
for j in range(m - 2, 0, -1):
	for i in range(n - 2, 0, -1):
		if arr[i][j] == 0:
			if arr[i + 1][j] != 0 and arr[i][j + 1] != 0:
				arr[i][j] = min(arr[i + 1][j] - 1, arr[i][j + 1] - 1)
row = True
col = True
for i in range(n):
	for j in range(m - 1, 0, -1):
		if not arr[i][j]:
			row = False
		if arr[i][j] <= arr[i][j - 1]:
			row = False
for j in range(m):
	for i in range(n - 1, 0, -1):
		if not arr[i][j]:
			col = False
		if arr[i][j] <= arr[i - 1][j]:
			col = False
if not row or not col:
	print(-1)
else:
	ans = 0
	for i in range(n):
		for j in range(m):
			ans += arr[i][j]
	print(ans)


(n, m) = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(n)]
res = 0
for i in range(n - 2, 0, -1):
	for j in range(m - 1, 0, -1):
		if matrix[i][j] == 0:
			mn = min(matrix[i + 1][j], matrix[i][j + 1])
			if mn != 1:
				matrix[i][j] = mn - 1
			else:
				res = -1
				break
	if res == -1:
		break
else:
	for i in range(n):
		if [matrix[i][j] for j in range(m - 1) if matrix[i][j] >= matrix[i][j + 1]]:
			res = -1
			break
	else:
		for j in range(m):
			if [matrix[i][j] for i in range(n - 1) if matrix[i][j] >= matrix[i + 1][j]]:
				res = -1
				break
		else:
			res = sum((sum(matrix[i]) for i in range(n)))
print(res)


__author__ = 'Esfandiar'
(n, m) = map(int, input().split())
a = list()
for i in range(n):
	a.append(list(map(int, input().split())))
su = 0
M = -1
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if a[i][j] == 0:
			M = a[i][j + 1] - 1
			M = min(M, a[i + 1][j] - 1)
			a[i][j] = M
		su += a[i][j]
for i in range(n):
	for j in range(m - 1):
		if a[i][j] >= a[i][j + 1]:
			print(-1)
			exit()
for i in range(m):
	for j in range(n - 1):
		if a[j][i] >= a[j + 1][i]:
			print(-1)
			exit()
print(su)


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	(n, m) = [int(x) for x in input().split()]
	mat = []
	for i in range(n):
		mat.append(list(map(int, input().rstrip().split())))
	z = 0
	for i in range(n - 1, 0, -1):
		for j in range(m - 1, 0, -1):
			e = mat[i][j]
			if mat[i][j] == 0:
				k = min(mat[i + 1][j], mat[i][j + 1]) - 1
				mat[i][j] = k
				if k <= max(mat[i - 1][j], mat[i][j - 1]):
					z = 1
					break
			elif e <= max(mat[i - 1][j], mat[i][j - 1]):
				z = 1
				break
		if z == 1:
			break
	if z == 1:
		print(-1)
	else:
		print(sum([sum(i) for i in mat]))
main()


(n, m) = list(map(int, input().split()))
a = []
for i in range(n):
	a.append(list(map(int, input().split())))

def result(a, n, m):
	r = 0
	for i in range(-1, -m, -1):
		if a[-1][i] == 0:
			a[-1][i] = a[-1][i + 1] - 1
		if a[-1][i] <= a[-1][i - 1] or a[-1][i] <= a[-2][i]:
			return -1
		r = r + a[-1][i]
	if a[-1][-m] == 0:
		a[-1][-m] = a[-1][-m + 1] - 1
	if a[-1][-m] <= a[-2][-m]:
		return -1
	r = r + a[-1][-m]
	for i in range(-2, -n, -1):
		for j in range(-1, -m, -1):
			if j == -1:
				if a[i][j] == 0:
					a[i][j] == a[i + 1][j] - 1
				if a[i][j] <= a[i][j - 1] or a[i][j] <= a[i - 1][j]:
					return -1
				r = r + a[i][j]
				continue
			if a[i][j] == 0:
				a[i][j] = min(a[i + 1][j] - 1, a[i][j + 1] - 1)
			if a[i][j] <= a[i - 1][j] or a[i][j] <= a[i][j - 1]:
				return -1
			r = r + a[i][j]
		if a[i][-m] == 0:
			a[i][-m] = min(a[i + 1][-m] - 1, a[i][-m + 1] - 1)
		if a[i][-m] <= a[i - 1][-m]:
			return -1
		r = r + a[i][-m]
	if a[0][-1] == 0:
		a[0][-1] = a[1][-1] - 1
	if a[0][-1] <= a[0][-2]:
		return -1
	r = r + a[0][-1]
	for i in range(-2, -m, -1):
		if a[0][i] == 0:
			a[0][i] = min(a[0][i + 1] - 1, a[1][i] - 1)
		if a[0][i] <= a[0][i - 1]:
			return -1
		r = r + a[0][i]
	if a[0][0] == 0:
		a[0][0] = min(a[0][1] - 1, a[1][0] - 1)
	r = r + a[0][0]
	return r
print(result(a, n, m))


(n, m) = map(int, input().split())
(matrix, result, ck) = ([], 0, False)
for _ in range(n):
	matrix.append(list(map(int, input().split())))
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if matrix[i][j] == 0:
			matrix[i][j] = min(matrix[i][j + 1], matrix[i + 1][j]) - 1
for i in range(n - 1):
	for j in range(m - 1):
		if matrix[i][j] >= matrix[i][j + 1] or matrix[i][j] >= matrix[i + 1][j]:
			ck = True
			break
		if ck:
			break
for row in matrix:
	result += sum(row)
if ck or matrix[-1][-1] <= matrix[-2][-1] or matrix[-1][-1] <= matrix[-1][-2]:
	print(-1)
else:
	print(result)


(n, m) = map(int, input().split())
arr = []
for i in range(n):
	sub_arr = list(map(int, input().split()))
	arr.append(sub_arr)
broken = 0
for i in range(n - 2, 0, -1):
	row = arr[i]
	for j in range(m - 2, 0, -1):
		ele = row[j]
		if ele != 0:
			continue
		else:
			maxim_y = arr[i + 1][j] - 1
			maxim_x = arr[i][j + 1] - 1
			if arr[i][j - 1] == 0:
				minim_x = 0
			else:
				minim_x = arr[i][j - 1] + 1
			if arr[i - 1][j] == 0:
				minim_y = 0
			else:
				minim_y = arr[i - 1][j]
			value = 0
			for k in range(maxim_x, minim_x - 1, -1):
				if k >= minim_y and k <= maxim_y:
					value = k
					break
			if value == 0:
				print(-1)
				broken += 1
				break
			else:
				arr[i][j] = value
	if broken > 0:
		break
ans = 0
if broken == 0:
	for i in range(n):
		row = arr[i]
		for j in range(1, m):
			if row[j] > row[j - 1]:
				continue
			else:
				broken += 1
				break
	for i in range(m):
		col = []
		for j in range(n):
			col.append(arr[j][i])
		for j in range(1, n):
			if col[j] > col[j - 1]:
				continue
			else:
				broken += 1
				break
	if broken > 0:
		print(-1)
		quit()
	for i in range(n):
		ans += sum(arr[i])
	print(ans)


(m, n) = map(int, input().split())
mat = [list(map(int, input().split())) for i in range(m)]
sum = 0
for i in range(m - 1, -1, -1):
	for j in range(n - 1, -1, -1):
		if mat[i][j] == 0:
			if i == m - 1:
				mat[i][j] = mat[i][j + 1] - 1
			elif j == n - 1:
				mat[i][j] = mat[i + 1][j] - 1
			else:
				mat[i][j] = min(mat[i][j + 1], mat[i + 1][j]) - 1
		sum += mat[i][j]
mark = 0
for i in range(m - 1, 0, -1):
	for j in range(n - 1, 0, -1):
		if mat[i][j] <= mat[i][j - 1] or mat[i][j] <= mat[i - 1][j]:
			mark = 1
			print(-1)
			break
	if mark == 1:
		break
if mark == 0:
	print(sum)


def rising(matr, n, m):
	s = matr[n - 1][m - 1]
	for j in range(m - 2, -1, -1):
		if matr[n - 1][j] < matr[n - 1][j + 1]:
			if matr[n - 1][j] == 0:
				matr[n - 1][j] = matr[n - 1][j + 1] - 1
			s += matr[n - 1][j]
		else:
			return -1
	for i in range(n - 2, -1, -1):
		if matr[i][m - 1] < matr[i + 1][m - 1]:
			if matr[i][m - 1] == 0:
				matr[i][m - 1] = matr[i + 1][m - 1] - 1
			s += matr[i][m - 1]
		else:
			return -1
	for i in range(n - 2, -1, -1):
		for j in range(m - 2, -1, -1):
			if matr[i][j] < min(matr[i + 1][j], matr[i][j + 1]):
				if matr[i][j] == 0:
					matr[i][j] = min(matr[i + 1][j], matr[i][j + 1]) - 1
				s += matr[i][j]
			else:
				return -1
	return s
(N, M) = [int(x) for x in input().split()]
matrix = list()
for y in range(N):
	row = [int(y) for y in input().split()]
	matrix.append(row)
print(rising(matrix, N, M))


a = [int(a) for a in input().split()]
b = list(list())
su = 0
ans = 0
cp = 0
for j in range(a[0]):
	c = [int(a) for a in input().split()][:a[1]]
	b.append(c)
for i in range(a[0] - 1, -1, -1):
	for j in range(a[1] - 1, -1, -1):
		if b[i][j] == 0:
			b[i][j] = int(min(b[i][j + 1], b[i + 1][j])) - 1
for z in b:
	for r in z:
		su += r
for i in range(a[0]):
	for j in range(a[1]):
		try:
			if b[i][j] >= b[i + 1][j]:
				ans = -1
				break
		except:
			cp += 1
		try:
			if b[i][j] >= b[i][j + 1]:
				ans = -1
				break
		except:
			cp += 1
if ans == -1:
	print(-1)
else:
	print(su)


(r, c) = tuple(map(int, input().split()))
arr = []
for _ in range(r):
	arr.append(list(map(int, input().split())))
flag = 0
for i in range(r - 2, 0, -1):
	j = c - 1
	while j >= 0:
		if arr[i][j] == 0:
			if arr[i + 1][j] - arr[i - 1][j] <= 1 or arr[i][j + 1] - arr[i][j - 1] <= 1 or arr[i + 1][j] - arr[i][j - 1] <= 1 or (arr[i][j + 1] - arr[i - 1][j] <= 1):
				flag = 1
				break
			else:
				arr[i][j] = min(arr[i][j + 1], arr[i + 1][j]) - 1
		j -= 1
	if flag:
		break
if flag:
	print(-1)
else:
	flag = 0
	for i in range(r):
		for j in range(c - 1):
			if arr[i][j] >= arr[i][j + 1]:
				flag = 1
				break
	for i in range(c):
		for j in range(r - 1):
			if flag:
				break
			elif arr[j][i] >= arr[j + 1][i]:
				flag = 1
				break
	if flag:
		print(-1)
	else:
		s = 0
		for i in arr:
			s += sum(i)
		print(s)


(n, m) = map(int, input().split())
x = [list(map(int, input().split())) for i in range(n)]
g = 0
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if x[i][j] == 0:
			a = min(x[i + 1][j] - 1, x[i][j + 1] - 1)
			b = max(x[i - 1][j] + 1, x[i][j - 1] + 1)
			if max(a, b) != x[i + 1][j] and max(a, b) != x[i][j + 1] and (max(a, b) != x[i - 1][j]) and (max(a, b) != x[i][j - 1]):
				x[i][j] = max(a, b)
			else:
				print(-1)
				exit()
for i in range(n):
	f = -1000
	for j in range(m):
		if x[i][j] <= f:
			print(-1)
			exit()
		else:
			f = x[i][j]
for i in range(m):
	f = -1000
	for j in range(n):
		if x[j][i] <= f:
			print(-1)
			exit()
		else:
			f = x[j][i]
for i in range(n):
	g += sum(x[i])
print(g)


(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
flag = 0
for i in range(1, n - 1)[::-1]:
	for j in range(1, m - 1)[::-1]:
		if a[i][j] == 0:
			a[i][j] = min(a[i + 1][j], a[i][j + 1]) - 1
for i in range(n):
	cnt = 0
	for j in range(m):
		if a[i][j] <= cnt:
			flag = 1
			break
		cnt = a[i][j]
	if flag:
		break
for i in range(m):
	cnt = 0
	for j in range(n):
		if a[j][i] <= cnt:
			flag = 1
			break
		cnt = a[j][i]
	if flag:
		break
if flag:
	print(-1)
else:
	ans = 0
	for i in range(n):
		ans += sum(a[i])
	print(ans)


def do():
	count = input()
	parsedCount = count.split(' ')
	row = int(parsedCount[0])
	column = int(parsedCount[1])
	matrix = []
	for i in range(0, row):
		matrix.append([int(i) for i in input().split(' ')])
	sum1 = 0
	for i in reversed(range(0, row)):
		for j in reversed(range(0, column)):
			if i == 0:
				upper = -1
			else:
				upper = matrix[i - 1][j]
			if j == column - 1:
				right = -1
			else:
				right = matrix[i][j + 1]
			if j == 0:
				left = -1
			else:
				left = matrix[i][j - 1]
			if i == row - 1:
				bottom = -1
			else:
				bottom = matrix[i + 1][j]
			if matrix[i][j] == 0:
				answer = min(right, bottom) - 1
				matrix[i][j] = answer
			if right != -1 and right <= matrix[i][j] or (bottom != -1 and bottom <= matrix[i][j]) or (upper != -1 and upper >= matrix[i][j]) or (left != -1 and left >= matrix[i][j]):
				print(-1)
				return
			sum1 += matrix[i][j]
	print(sum1)
do()


(n, m) = map(int, input().split(' '))
mat = []
for _ in range(n):
	mat.append(list(map(int, input().split(' '))))
try:
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if mat[i][j] == 0:
				mat[i][j] = min(mat[i + 1][j], mat[i][j + 1]) - 1
			if i + 1 < n:
				assert mat[i][j] < mat[i + 1][j]
			if j + 1 < m:
				assert mat[i][j] < mat[i][j + 1]
	print(sum(map(sum, mat)))
except AssertionError:
	print(-1)


def solution():
	(m, n) = map(int, input().split())
	matrix = []
	for i in range(m):
		matrix.append(list(map(int, input().split())))
	sum = 0
	for i in reversed(range(m)):
		for j in reversed(range(n)):
			if matrix[i][j] == 0:
				matrix[i][j] = min(matrix[i + 1][j], matrix[i][j + 1]) - 1
			elif i < m - 1 and j < n - 1:
				if matrix[i][j] >= matrix[i + 1][j] or matrix[i][j] >= matrix[i][j + 1]:
					print(-1)
					return
			elif i < m - 1:
				if matrix[i][j] >= matrix[i + 1][j]:
					print(-1)
					return
			elif j < n - 1:
				if matrix[i][j] >= matrix[i][j + 1]:
					print(-1)
					return
			sum += matrix[i][j]
	print(sum)
solution()


import math, sys
from collections import defaultdict, Counter, deque
INF = float('inf')
MOD = int(1000000000.0) + 7

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def isPrime(n):
	if n <= 1:
		return False
	i = 2
	while i ** 2 <= n:
		if n % i == 0:
			return False
		i += 1
	return True

def primeFactors(n):
	factors = defaultdict(int)
	i = 2
	while i ** 2 <= n:
		while n % i == 0:
			factors[i] += 1
			n //= i
		i += 1
	if n > 1:
		factors[n] += 1
	return factors

def vars():
	return map(int, input().split())

def array():
	return list(map(int, input().split()))

def main():
	(n, m) = vars()
	mat = []
	for i in range(n):
		mat.append(array())
	ans = 0
	for i in range(n):
		for j in range(m):
			if mat[i][j]:
				if i > 0 and mat[i][j] <= mat[i - 1][j]:
					print(-1)
					return
				if j > 0 and mat[i][j] <= mat[i][j - 1]:
					print(-1)
					return
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if mat[i][j] == 0:
				num = min(mat[i][j + 1], mat[i + 1][j]) - 1
				if num > mat[i - 1][j] and num > mat[i][j - 1]:
					mat[i][j] = num
				else:
					print(-1)
					return
			ans += mat[i][j]
	print(ans)
	return
t = 1
for _ in range(t):
	main()


(n, m) = list(map(int, input().split(' ')))
matrix = []
matrix.append([])
for i in range(n):
	matrix.append(list(map(int, input().split(' '))))
	matrix[i + 1].insert(0, -1)
flag = True
soma = 0
for i in range(1, n + 1):
	for j in range(1, m + 1):
		soma += matrix[i][j]
for i in range(n, 0, -1):
	for j in range(m, 0, -1):
		if matrix[i][j] == 0:
			matrix[i][j] = min(matrix[i + 1][j], matrix[i][j + 1]) - 1
			soma += matrix[i][j]
		elif i < n and matrix[i][j] >= matrix[i + 1][j] or (j < m and matrix[i][j] >= matrix[i][j + 1]):
			flag = False
			break
if flag:
	print(soma)
else:
	print(-1)


(n, m) = map(int, input().split())
r = []
sum = 0
for x in range(n):
	r.append(list(input().split()))
for x in range(n - 1, -1, -1):
	for y in range(m - 1, -1, -1):
		if r[x][y] == '0':
			if int(r[x + 1][y]) < int(r[x][y + 1]):
				r[x][y] = str(int(r[x + 1][y]) - 1)
			else:
				r[x][y] = str(int(r[x][y + 1]) - 1)
		sum += int(r[x][y])
for x in range(n):
	for y in range(m - 1):
		if int(r[x][y]) >= int(r[x][y + 1]):
			sum = -1
			break
	if sum == -1:
		break
if sum != -1:
	for x in range(n - 1):
		for y in range(m):
			if int(r[x][y]) >= int(r[x + 1][y]):
				sum = -1
				break
		if sum == -1:
			break
print(sum)


(n, m) = map(int, input().split())
mat = []
tot = 0
for i in range(n):
	a = list(map(int, input().split()))
	tot += sum(a)
	mat.append(a)
for i in reversed(range(n)):
	for j in reversed(range(m)):
		if mat[i][j] == 0:
			mat[i][j] = min(mat[i + 1][j], mat[i][j + 1]) - 1
			tot += mat[i][j]
b = False
c = False
for i in range(n):
	for j in range(m - 1):
		if mat[i][j] >= mat[i][j + 1]:
			b = True
			break
	if b:
		break
for j in range(m):
	for i in range(n - 1):
		if mat[i][j] >= mat[i + 1][j]:
			c = True
			break
	if c:
		break
if b or c:
	print(-1)
else:
	print(tot)


(n, m) = map(int, input().split())
matrix = []
for i in range(n):
	matrix.append(list(map(int, input().split())))
for i in range(n - 1, 0, -1):
	for j in range(m - 1, 0, -1):
		if matrix[i][j] == 0:
			matrix[i][j] = min(matrix[i + 1][j], matrix[i][j + 1]) - 1
count = 0
for i in range(n - 1):
	flag = True
	for j in range(m - 1):
		if matrix[i][j] >= matrix[i + 1][j] or matrix[i][j] >= matrix[i][j + 1]:
			flag = False
			break
	for j in range(m - 1):
		if matrix[n - 1][j] >= matrix[n - 1][j + 1]:
			flag = False
			break
	if matrix[i][m - 1] >= matrix[i + 1][m - 1]:
		flag = False
	if flag == False:
		print(-1)
		break
else:
	for i in range(n):
		for j in range(m):
			count += matrix[i][j]
	print(count)


def main():
	(n, m) = readIntArr()
	arr = []
	for _ in range(n):
		arr.append(readIntArr())
	for i in range(n - 2, 0, -1):
		for j in range(m - 2, 0, -1):
			if arr[i][j] == 0:
				arr[i][j] = min(arr[i + 1][j], arr[i][j + 1]) - 1
	for i in range(n):
		for j in range(m):
			if i - 1 >= 0 and arr[i - 1][j] >= arr[i][j]:
				print(-1)
				return
			if j - 1 >= 0 and arr[i][j - 1] >= arr[i][j]:
				print(-1)
				return
	ans = 0
	for i in range(n):
		for j in range(m):
			ans += arr[i][j]
	print(ans)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(i, j):
	print('? {} {}'.format(i, j))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(' '.join([str(x) for x in ans])))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


def check(a, n, m):
	for x in a:
		for i in range(m - 1):
			if x[i] >= x[i + 1]:
				return False
	for i in range(m):
		for j in range(n - 1):
			if a[j][i] >= a[j + 1][i]:
				return False
	return True
(n, m) = list(map(int, input().split()))
a = list((list(map(int, input().split())) for _ in range(n)))
sum = 0
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if not a[i][j]:
			a[i][j] = min(a[i + 1][j], a[i][j + 1]) - 1
		sum += a[i][j]
print(sum if check(a, n, m) else -1)


import sys
count = 0
matrix = []
for line in sys.stdin:
	if count == 0:
		depth = int(line.strip().split(' ')[0])
		width = int(line.strip().split(' ')[1])
		count += 1
		continue
	tmp = [int(s) for s in line.strip().split(' ')]
	matrix.append(tmp)
flag = 0
res = 0
for i in range(depth - 2, 0, -1):
	for j in range(width - 2, 0, -1):
		if matrix[i][j] == 0:
			matrix[i][j] = min(matrix[i + 1][j], matrix[i][j + 1]) - 1
for i in range(depth):
	for j in range(width):
		res += matrix[i][j]
		if i < depth - 1 and matrix[i][j] >= matrix[i + 1][j] or (j < width - 1 and matrix[i][j] >= matrix[i][j + 1]):
			flag = -1
			break
res = -1 if flag == -1 else res
print(res)


(n, m) = map(int, input().split())
arr = []
for i in range(n):
	arr.append(list(map(int, input().split())))
for i in range(n - 2, 0, -1):
	for j in range(m - 2, 0, -1):
		if arr[i][j] == 0:
			arr[i][j] = min(arr[i + 1][j], arr[i][j + 1]) - 1
summ = 0
for i in range(n):
	prev = -1
	for j in range(m):
		if arr[i][j] <= prev:
			print(-1)
			exit()
		summ += arr[i][j]
		prev = arr[i][j]
for j in range(m):
	prev = -1
	for i in range(n):
		if arr[i][j] <= prev:
			print(-1)
			exit()
		prev = arr[i][j]
print(summ)


import math

def checker(matrix, n, m, s):
	z = 0
	for i in range(0, n):
		for j in range(0, m - 1):
			if matrix[i][j] < matrix[i][j + 1]:
				continue
			else:
				z = 1
				break
	if z == 1:
		print('-1')
	else:
		for i in range(0, n - 1):
			for j in range(0, m):
				if matrix[i][j] < matrix[i + 1][j]:
					continue
				else:
					z = 1
					break
		if z == 0:
			print(s)
		else:
			print('-1')
(n, m) = list(map(int, input().split()))
matrix = []
s = 0
e = []
f = []
for i in range(0, n):
	a = list(map(int, input().split()))
	for j in range(0, m):
		if a[j] == 0:
			e.append(i)
			f.append(j)
		else:
			continue
	s += int(sum(a))
	matrix.append(a)
e = e[::-1]
f = f[::-1]
if len(e) == 0:
	checker(matrix, n, m, s)
else:
	for i in range(0, len(e)):
		g = int(matrix[e[i] + 1][f[i]])
		h = int(matrix[e[i]][f[i] + 1])
		c = g - h
		c = int(math.fabs(c))
		d = min(g, h) - 1
		s += d
		matrix[e[i]][f[i]] = d
	checker(matrix, n, m, s)


def read():
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	return (n, m, a)

def solve(n, m, a):
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if a[i][j] == 0:
				if i == n - 1:
					if j == m - 1:
						a[i][j] = 8000
					else:
						a[i][j] = a[i][j + 1] - 1
				elif j == m - 1:
					a[i][j] = a[i + 1][j] - 1
				else:
					a[i][j] = min(a[i + 1][j], a[i][j + 1]) - 1
			if not ((i == 0 or a[i][j] > a[i - 1][j]) and (j == 0 or a[i][j] > a[i][j - 1])):
				return -1
	s = 0
	for i in range(n):
		for j in range(m):
			s += a[i][j]
	return s
result = solve(*read())
print(result)