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
Tags: Greedy algorithms
Skill types: Greedy algorithms

Starter code:

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

def getGreatest(left, right, top, down):
	x = right - 1
	while x != left and x != top:
		if x < right and x > left and (x > top) and (x < down):
			return x
		x -= 1
	return '-1'

def summ(matrix, n, m):
	s = 0
	for i in range(n):
		for j in range(m):
			s += matrix[i][j]
	return s
inp = input().split()
n = int(inp[0])
m = int(inp[1])
matrix = []
for i in range(n):
	row = list(map(int, input().split()))
	matrix.append(row)
for i in range(n - 2, 0, -1):
	for j in range(m - 2, 0, -1):
		if matrix[i][j] == 0:
			test = getGreatest(matrix[i][j - 1], matrix[i][j + 1], matrix[i - 1][j], matrix[i + 1][j])
			if test != '-1':
				matrix[i][j] = test
			else:
				print('-1')
				sys.exit()
for i in range(n - 1):
	for j in range(m):
		if matrix[i][j] >= matrix[i + 1][j]:
			print('-1')
			sys.exit()
for i in range(n):
	for j in range(m - 1):
		if matrix[i][j] >= matrix[i][j + 1]:
			print('-1')
			sys.exit()
s = summ(matrix, n, m)
print(s)


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()


(n, m) = map(int, input().split())
mat = [list(map(int, input().split())) for _ in range(n)]
ok = True
sums = 0
for i in range(n):
	for j in range(m):
		if mat[n - i - 2][m - j - 2] == 0:
			mat[n - i - 2][m - j - 2] = min(mat[n - i - 2][m - j - 1], mat[n - i - 1][m - j - 2]) - 1
		if n - i - 1 > 0:
			if mat[n - i - 1][m - j - 1] <= mat[n - i - 2][m - j - 1]:
				ok = False
		if m - j - 1 > 0:
			if mat[n - i - 1][m - j - 1] <= mat[n - i - 1][m - j - 2]:
				ok = False
for i in range(n):
	for j in range(m):
		sums += mat[i][j]
if ok:
	print(sums)
else:
	print(-1)


n_m = input()
n_m = n_m.split()
n = int(n_m[0])
m = int(n_m[1])
A = list()
i = 0
while i < n:
	A.append(list())
	row = input()
	row = row.split()
	j = 0
	while j < m:
		A[i].append(int(row[j]))
		j = j + 1
	i = i + 1
step_1 = True
k = n - 1
i = m - 2
while i >= 0:
	if A[k][i] < A[k][i + 1]:
		if A[k][i] == 0:
			A[k][i] = A[k][i + 1] - 1
	else:
		step_1 = False
		break
	i = i - 1
if step_1 == True:
	step_2 = True
	k = m - 1
	i = n - 2
	while i >= 0:
		if A[i][k] < A[i + 1][k]:
			if A[i][k] == 0:
				A[i][k] = A[i][k + 1] - 1
		else:
			step_2 = False
			break
		i = i - 1
	if step_2 == True:
		step_3 = True
		i = n - 2
		while i >= 0:
			j = m - 2
			while j >= 0:
				if A[i][j + 1] < A[i + 1][j]:
					min = A[i][j + 1]
				else:
					min = A[i + 1][j]
				if A[i][j] < min:
					if A[i][j] == 0:
						A[i][j] = min - 1
				else:
					step_3 = False
					break
				j = j - 1
			if step_3 == True:
				i = i - 1
			else:
				break
		if step_3 == True:
			amount = 0
			i = 0
			while i < n:
				j = 0
				while j < m:
					amount = amount + A[i][j]
					j = j + 1
				i = i + 1
			print(amount)
		else:
			print(-1)
	else:
		print(-1)
else:
	print(-1)


(n, m) = list(map(int, input().split(' ')))
(a, sum) = ([], 0)
for i in range(n):
	a.append(list(map(int, input().split(' '))))
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][j + 1], a[i + 1][j]) - 1
		sum += a[i][j]
for i in range(n):
	for j in range(1, m):
		if a[i][j] <= a[i][j - 1]:
			print(-1)
			exit()
for i in range(m):
	for j in range(1, n):
		if a[j][i] <= a[j - 1][i]:
			print(-1)
			exit()
print(sum)


(n, m) = map(int, input().split())
matr = [list(map(int, input().split())) for i in range(n)]
k = 0
for i in range(n - 1, 0, -1):
	for j in range(m - 1, 0, -1):
		if matr[i - 1][j - 1] == 0:
			matr[i - 1][j - 1] = min(matr[i - 1][j], matr[i][j - 1]) - 1
		if matr[i][j] <= matr[i - 1][j]:
			k = 1
			break
		if matr[i][j] <= matr[i][j - 1]:
			k = 1
			break
	if k == 1:
		break
if k == 1:
	print(-1)
else:
	res = 0
	for (i, x) in enumerate(matr):
		res += sum(x)
	print(res)


(n, m) = list(map(int, input().split()))
k = 0
a = [0] * n
for i in range(n):
	a[i] = list(map(int, input().split()))
b = [0] * n
c = [0] * n
for i in range(n):
	b[i] = [0] * m
	c[i] = [0] * m
	for j in range(m):
		b[i][j] = [0, 0]
		c[i][j] = [0, 0]
for i in range(n):
	for j in range(m - 1):
		if a[i][j] >= a[i][j + 1] and a[i][j + 1] != 0:
			k = 1
for j in range(m):
	for i in range(n - 1):
		if a[i][j] >= a[i + 1][j] and a[i + 1][j] != 0:
			k = 1
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] - 1, a[i][j + 1] - 1)
for i in range(n):
	for j in range(m - 1):
		if a[i][j] >= a[i][j + 1] and a[i][j + 1] != 0:
			k = 1
for j in range(m):
	for i in range(n - 1):
		if a[i][j] >= a[i + 1][j] and a[i + 1][j] != 0:
			k = 1
ans = 0
for i in range(n):
	ans += sum(a[i])
if k == 1:
	print(-1)
else:
	print(ans)


import sys
import math
import bisect

def solve(A):
	n = len(A)
	m = len(A[0])
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if A[i][j] == 0:
				min_val = 10 ** 18
				if i + 1 < n:
					min_val = min(min_val, A[i + 1][j])
				if j + 1 < m:
					min_val = min(min_val, A[i][j + 1])
				if min_val == 0:
					return False
				else:
					A[i][j] = min_val - 1
			else:
				if i + 1 < n and A[i][j] >= A[i + 1][j]:
					return False
				if j + 1 < m and A[i][j] >= A[i][j + 1]:
					return False
	return True

def main():
	(n, m) = map(int, input().split())
	A = []
	for i in range(n):
		A.append(list(map(int, input().split())))
	if solve(A):
		ans = 0
		for i in range(n):
			ans += sum(A[i])
		print(ans)
	else:
		print(-1)
main()


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


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()


def solve(arr, n, k):
	s = 0
	for i in reversed(range(n)):
		for j in reversed(range(k)):
			if arr[i][j] == 0:
				m = min(arr[i + 1][j], arr[i][j + 1])
				if m == 1:
					return -1
				arr[i][j] = m - 1
			s += arr[i][j]
			if j > 0 and arr[i][j - 1] >= arr[i][j]:
				return -1
			if i > 0 and arr[i - 1][j] >= arr[i][j]:
				return -1
	return s
(n, k) = [int(x) for x in input().split()]
arr = []
for _ in range(n):
	arr.append([int(x) for x in input().split()])
res = solve(arr, n, k)
print(res)


(n, m) = map(int, input().split())
l = []
for i in range(n):
	l.append(list(map(int, input().split())))
s = 0
for i in range(len(l) - 1, -1, -1):
	for j in range(len(l[i]) - 1, -1, -1):
		if l[i][j] == 0:
			r1 = l[i][j + 1] - 1
			r2 = l[i + 1][j] - 1
			r3 = min(r1, r2)
			l[i][j] = r3
		s = s + l[i][j]
f = 0
for i in range(len(l)):
	for j in range(len(l[i]) - 1):
		if l[i][j] < l[i][j + 1]:
			pass
		else:
			f = 1
			break
for i in range(len(l) - 1):
	for j in range(len(l[i])):
		if l[i][j] < l[i + 1][j]:
			pass
		else:
			f = 1
			break
if f == 0:
	print(s)
else:
	print(-1)


(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)


(n, m) = map(int, input().split())
a = [[int(i) for i in 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 a[i][j] == 0:
			temp = min(a[i + 1][j], a[i][j + 1]) - 1
			if temp > max(a[i - 1][j], a[i][j - 1]):
				ans += temp
				a[i][j] = temp
			else:
				print(-1)
				exit(0)
		else:
			ans += a[i][j]
			if 0 < i < n - 1:
				if a[i - 1][j] < a[i][j] < a[i + 1][j]:
					continue
				else:
					print(-1)
					exit(0)
			if 0 < j < m - 1:
				if a[i][j - 1] < a[i][j] < a[i][j + 1]:
					continue
				else:
					print(-1)
					exit(0)
print(ans)


(n, m) = list(map(int, input().split()))
a = []
for _ in range(n):
	a.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 a[i][j] == 0:
			l = min(a[i + 1][j] - 1, a[i][j + 1] - 1)
			a[i][j] = l
		s += 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(n - 1):
	for j in range(m):
		if a[i][j] >= a[i + 1][j]:
			print(-1)
			exit()
print(s)


I = input
(rows, cols) = map(int, I().split())
matrix = [list(map(int, I().split())) for i in range(rows)]
result = 0
for i in range(rows - 1):
	if matrix[i][cols - 1] >= matrix[i + 1][cols - 1]:
		print(-1)
		exit()
for row_index in range(rows - 1, -1, -1):
	for col_index in range(cols - 2, -1, -1):
		if row_index == rows - 1:
			matrix[row_index][col_index] = matrix[row_index][col_index + 1] - 1 if matrix[row_index][col_index] == 0 else matrix[row_index][col_index]
			if matrix[row_index][col_index] >= matrix[row_index][col_index + 1]:
				print(-1)
				exit()
		else:
			if matrix[row_index][col_index] == 0:
				matrix[row_index][col_index] = min(matrix[row_index + 1][col_index] - 1, matrix[row_index][col_index + 1] - 1)
			if matrix[row_index][col_index] >= matrix[row_index][col_index + 1] or matrix[row_index][col_index] >= matrix[row_index + 1][col_index]:
				print(-1)
				exit()
	result += sum(matrix[row_index])
print(result)


(n, m) = map(int, input().split())
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
ok = True
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
for i in range(n):
	for j in range(1, m):
		if a[i][j] != 0 and a[i][j - 1] != 0 and (a[i][j] <= a[i][j - 1]):
			ok = False
for j in range(m):
	for i in range(1, n):
		if a[i][j] != 0 and a[i - 1][j] != 0 and (a[i][j] <= a[i - 1][j]):
			ok = False
if ok:
	s = 0
	for i in a:
		s += sum(i)
	print(s)
else:
	print(-1)


I = lambda : map(int, input().split())
(n, m) = I()
A = [list(I()) for _ in range(n)]
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 all((A[i][j] < A[i][j + 1] for i in range(n) for j in range(m - 1))) and all((A[i][j] < A[i + 1][j] for i in range(n - 1) for j in range(m))):
	print(sum((A[i][j] for i in range(n) for j in range(m))))
else:
	print(-1)


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


(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 check(w):
	for i in range(len(w)):
		a = w[i]
		for j in range(1, len(a)):
			if a[j] <= a[j - 1]:
				return 0
	w = list(zip(*w))
	for i in range(len(w)):
		a = w[i]
		for j in range(1, len(a)):
			if a[j] <= a[j - 1]:
				return 0
	return 1
import sys
(n, m) = map(int, input().split())
w = []
for i in range(n):
	hh = list(map(int, input().split()))
	w.append(hh)
tot = 0
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if w[i][j] == 0:
			w[i][j] = min(w[i][j + 1], w[i + 1][j]) - 1
			if w[i][j] <= w[i][j - 1] or w[i][j] <= w[i - 1][j]:
				print(-1)
				sys.exit()
		tot += w[i][j]
if check(w):
	print(tot)
else:
	print(-1)


def shuru(t=0, s=0):
	in_item = input().strip()
	if not t:
		return in_item
	elif not s:
		str_t = t + '(' + in_item + ')'
		in_item = eval(str_t)
		return in_item
	else:
		str_s = 'list(' + s + '(lambda x:int(x) ,in_item.split() ))'
		return eval(str_s)

def fun2():
	(n, m) = shuru('int', 'map')
	res = []
	for i in range(n):
		res.append(shuru('int', 'map'))
	res_sum = 0
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if res[i][j] == 0:
				res[i][j] = min(res[i + 1][j], res[i][j + 1])
				res[i][j] -= 1
			if res[i][j] <= 0:
				print(-1)
				return
			if i > 0 and j > 0:
				if res[i][j] <= res[i - 1][j] or res[i][j] <= res[i][j - 1]:
					print(-1)
					return
			if j == 0 and i != 0 and (res[i][0] <= res[i - 1][0]):
				print(-1)
				return
			if i == 0 and j != 0 and (res[0][j] <= res[0][j - 1]):
				print(-1)
				return
			res_sum += res[i][j]
	print(res_sum)
fun2()


from __future__ import division, print_function
import math
import os
import sys
from fractions import *
from sys import *
from decimal import *
from io import BytesIO, IOBase
from itertools import accumulate, combinations, permutations, combinations_with_replacement, product
from collections import *
import timeit, time
M = 10 ** 9 + 7
import heapq
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
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 inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def inpu():
	return int(inp())

def regularbracket(t):
	p = 0
	for i in t:
		if i == '(':
			p += 1
		else:
			p -= 1
		if p < 0:
			return False
	else:
		if p > 0:
			return False
		else:
			return True

def binarySearchcount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def binarySearch(arr, n, key):
	left = 0
	right = n - 1
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] == key:
			return mid
		if arr[mid] <= key:
			left = mid + 1
		else:
			right = mid - 1
	return -1

def ternarysearch(arr, n, key):
	(l, r) = (0, n - 1)
	while l <= r:
		mid = (-l + r) // 3 + l
		mid2 = mid + (-l + r) // 3
		if arr[mid] == key:
			return mid
		if arr[mid2] == key:
			return mid2
		if arr[mid] > key:
			r = mid - 1
		elif arr[mid2] < key:
			l = mid2 + 1
		else:
			l = mid + 1
			r = mid2 - 1
	return -1

def reverse1(string):
	pp = ''
	for i in string[::-1]:
		pp += i
	if pp == string:
		return True
	return False

def reverse2(list1):
	l = []
	for i in list1[::-1]:
		l.append(i)
	if l == list1:
		return True
	return False

def mex(list1):
	p = max(list1) + 1
	for i in range(len(list1)):
		if list1[i] != i:
			p = i
			break
	return p

def sumofdigits(n):
	n = str(n)
	s1 = 0
	for i in n:
		s1 += int(i)
	return s1

def perfect_square(n):
	s = math.sqrt(n)
	if s == int(s):
		return True
	return False

def roman_number(x):
	if x > 15999:
		return
	value = [5000, 4000, 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
	symbol = ['F', 'MF', 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
	roman = ''
	i = 0
	while x > 0:
		div = x // value[i]
		x = x % value[i]
		while div:
			roman += symbol[i]
			div -= 1
		i += 1
	return roman

def soretd(s):
	for i in range(1, len(s)):
		if s[i - 1] > s[i]:
			return False
	return True

def countRhombi(h, w):
	ct = 0
	for i in range(2, h + 1, 2):
		for j in range(2, w + 1, 2):
			ct += (h - i + 1) * (w - j + 1)
	return ct

def countrhombi2(h, w):
	return h * h // 4 * (w * w // 4)

def binpow(a, b):
	if b == 0:
		return 1
	else:
		res = binpow(a, b // 2)
	if b % 2 != 0:
		return res * res * a
	else:
		return res * res

def binpowmodulus(a, b, m):
	a %= m
	res = 1
	while b > 0:
		if b & 1:
			res = res * a % m
		a = a * a % m
		b >>= 1
	return res

def coprime_to_n(n):
	result = n
	i = 2
	while i * i <= n:
		if n % i == 0:
			while n % i == 0:
				n //= i
			result -= result // i
		i += 1
	if n > 1:
		result -= result // n
	return result

def luckynumwithequalnumberoffourandseven(x, n, a):
	if x >= n and str(x).count('4') == str(x).count('7'):
		a.append(x)
	elif x < 1000000000000.0:
		luckynumwithequalnumberoffourandseven(x * 10 + 4, n, a)
		luckynumwithequalnumberoffourandseven(x * 10 + 7, n, a)
	return a

def luckynum(x, l, r, a):
	if x >= l and x <= r:
		a.append(x)
	if x > r:
		a.append(x)
		return a
	if x < 10000000000.0:
		luckynum(x * 10 + 4, l, r, a)
		luckynum(x * 10 + 7, l, r, a)
	return a

def luckynuber(x, n, a):
	p = set(str(x))
	if len(p) <= 2:
		a.append(x)
	if x < n:
		luckynuber(x + 1, n, a)
	return a

def interact(type, x):
	if type == 'r':
		inp = input()
		return inp.strip()
	else:
		print(x, flush=True)

def findTrailingZeros(n):
	count = 0
	while n >= 5:
		n //= 5
		count += n
	return count

def mergeSort(arr):
	if len(arr) > 1:
		mid = len(arr) // 2
		L = arr[:mid]
		R = arr[mid:]
		mergeSort(L)
		mergeSort(R)
		i = j = k = 0
		while i < len(L) and j < len(R):
			if L[i] < R[j]:
				arr[k] = L[i]
				i += 1
			else:
				arr[k] = R[j]
				j += 1
			k += 1
		while i < len(L):
			arr[k] = L[i]
			i += 1
			k += 1
		while j < len(R):
			arr[k] = R[j]
			j += 1
			k += 1
res = set()

def solven(p, l, a, b, n):
	if p > n or l > 10:
		return
	if p > 0:
		res.add(p)
	solven(p * 10 + a, l + 1, a, b, n)
	solven(p * 10 + b, l + 1, a, b, n)

def subsetsUtil(A, subset, index, d):
	print(*subset)
	s = sum(subset)
	d.append(s)
	for i in range(index, len(A)):
		subset.append(A[i])
		subsetsUtil(A, subset, i + 1, d)
		subset.pop(-1)
	return d

def subsetSums(arr, l, r, d, sum=0):
	if l > r:
		d.append(sum)
		return
	subsetSums(arr, l + 1, r, d, sum + arr[l])
	subsetSums(arr, l + 1, r, d, sum)
	return d

def print_factors(x):
	factors = []
	for i in range(1, x + 1):
		if x % i == 0:
			factors.append(i)
	return factors

def calc(X, d, ans, D):
	if len(X) == 0:
		return
	i = X.index(max(X))
	ans[D[max(X)]] = d
	Y = X[:i]
	Z = X[i + 1:]
	calc(Y, d + 1, ans, D)
	calc(Z, d + 1, ans, D)

def factorization(n, l):
	c = n
	if prime(n) == True:
		l.append(n)
		return l
	for i in range(2, c):
		if n == 1:
			break
		while n % i == 0:
			l.append(i)
			n = n // i
	return l

def good(b):
	l = []
	i = 0
	while len(b) != 0:
		if b[i] < b[len(b) - 1 - i]:
			l.append(b[i])
			b.remove(b[i])
		else:
			l.append(b[len(b) - 1 - i])
			b.remove(b[len(b) - 1 - i])
	if l == sorted(l):
		return True
	return False

def generate(st, s):
	if len(s) == 0:
		return
	if s not in st:
		st.add(s)
		for i in range(len(s)):
			t = list(s).copy()
			t.remove(s[i])
			t = ''.join(t)
			generate(st, t)
	return

def largestincreasingsubsequence(A):
	l = [1] * len(A)
	sub = []
	for i in range(1, len(l)):
		for k in range(i):
			if A[k] < A[i]:
				sub.append(l[k])
		l[i] = 1 + max(sub, default=0)
	return max(l, default=0)

def findOR(nums, N):
	prefix_sum = 0
	result = 0
	for i in range(N):
		result |= nums[i]
		prefix_sum += nums[i]
		result |= prefix_sum
	return result

def OR(a, n):
	ans = a[0]
	for i in range(1, n):
		ans |= a[i]
	return ans

def toString(List):
	return ''.join(List)

def permute(a, l, r, p):
	if l == r:
		p.append(toString(a))
	else:
		for i in range(l, r + 1):
			(a[l], a[i]) = (a[i], a[l])
			permute(a, l + 1, r, p)
			(a[l], a[i]) = (a[i], a[l])

def squareRoot(number, precision):
	start = 0
	(end, ans) = (number, 1)
	while start <= end:
		mid = int((start + end) / 2)
		if mid * mid == number:
			ans = mid
			break
		if mid * mid < number:
			start = mid + 1
		else:
			end = mid - 1
	increment = 0.1
	for i in range(0, precision):
		while ans * ans <= number:
			ans += increment
		ans = ans - increment
		increment = increment / 10
	return ans

def countRectangles(l, w):
	squareSide = math.gcd(l, w)
	return int(l * w / (squareSide * squareSide))

def count_same_digit(L, R):
	tmp = 0
	ans = 0
	n = int(math.log10(R) + 1)
	for i in range(0, n):
		tmp = tmp * 10 + 1
		for j in range(1, 10):
			if L <= tmp * j and tmp * j <= R:
				ans += 1
	return ans

def findCrossOver(arr, low, high, x):
	if arr[high] <= x:
		return high
	if arr[low] > x:
		return low
	mid = (low + high) // 2
	if arr[mid] <= x and arr[mid + 1] > x:
		return mid
	if arr[mid] < x:
		return findCrossOver(arr, mid + 1, high, x)
	return findCrossOver(arr, low, mid - 1, x)

def Kclosest(arr, x, k, n, ans):
	l = findCrossOver(arr, 0, n - 1, x)
	r = l + 1
	count = 0
	if arr[l] == x:
		l -= 1
	while l >= 0 and r < n and (count < k):
		if x - arr[l] < arr[r] - x:
			ans.append(arr[l])
			l -= 1
		else:
			ans.append(arr[r])
			r += 1
		count += 1
	while count < k and l >= 0:
		ans.append(arr[l])
		l -= 1
		count += 1
	while count < k and r < n:
		ans.append(arr[r])
		r += 1
		count += 1
	return ans

def prime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	for i in range(5, int(math.sqrt(n)) + 1, 2):
		if n % i == 0:
			return False
	return True

def calcSum(arr, n, k):
	l = []
	sum = 0
	for i in range(k):
		sum += arr[i]
	l.append(sum)
	for i in range(k, n):
		sum = sum - arr[i - k] + arr[i]
		l.append(sum)
	return l

def dfs(root, nodeVal, nodeConnection, visited):
	leftVal = nodeVal[root][0]
	rightVal = nodeVal[root][1]
	solution = []
	if nodeConnection[root]:
		visited.add(root)
		for i in nodeConnection[root]:
			if i not in visited:
				solution.append(dfs(i, nodeVal, nodeConnection, visited))
		leftMax = 0
		rightMax = 0
		for i in solution:
			(l, r) = i
			leftMax += max(abs(leftVal - l[0]) + l[1], abs(leftVal - r[0]) + r[1])
			rightMax += max(abs(rightVal - l[0]) + l[1], abs(rightVal - r[0]) + r[1])
		return ((leftVal, leftMax), (rightVal, rightMax))
	else:
		return ((leftVal, 0), (rightVal, 0))

def luckynumber(x, n, a):
	if x > 0:
		a.append(x)
	if x > 10 ** 9:
		return a
	elif x < 1000000000000.0:
		luckynumber(x * 10 + 4, n, a)
		luckynumber(x * 10 + 7, n, a)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def query(l, r):
	if l >= r:
		return -1
	print('?', l + 1, r + 1)
	sys.stdout.flush()
	return int(input()) - 1

def answer(p):
	print('!', p + 1)
	sys.stdout.flush()
	exit()

def main():
	(n, m) = sep()
	l = []
	for i in range(n):
		l.append(lis())
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if l[i][j] == 0:
				l[i][j] = min(l[i + 1][j], l[i][j + 1]) - 1
	flag = 1
	for i in range(n):
		for j in range(m):
			if i + 1 < n and l[i][j] >= l[i + 1][j] or (j + 1 < m and l[i][j] >= l[i][j + 1]) or (i - 1 >= 0 and l[i][j] <= l[i - 1][j]) or (j - 1 >= 0 and l[i][j] <= l[i][j - 1]):
				flag = 0
				break
	ans = 0
	if flag == 0:
		print(-1)
	else:
		for i in range(n):
			for j in range(m):
				ans += l[i][j]
		print(ans)
main()


(m, n) = map(int, input().split())
a = []
for _ in range(m):
	a.append(list(map(int, input().split())))
f = 0
for i in range(n):
	if a[m - 1][i] - a[0][i] < m - 1:
		f = 1
		break
	if i < n - 1:
		if a[m - 1][i] >= a[m - 1][i + 1] or a[0][i] >= a[0][i + 1]:
			f = 1
			break
if f == 0:
	for i in range(m):
		if a[i][n - 1] - a[i][0] < n - 1:
			f = 1
			break
		if i < m - 1:
			if a[i][n - 1] >= a[i + 1][n - 1] or a[i][0] >= a[i + 1][0]:
				f = 1
				break
if f == 0:
	i = m - 1
	j = n - 1
	sum1 = 0
	while j >= 0:
		if a[i][j] == 0:
			min1 = min(a[i][j + 1] - 1, a[i + 1][j] - 1)
			if min1 <= max(a[i][j - 1], a[i - 1][j]):
				f = 1
			else:
				a[i][j] = min1
		sum1 += a[i][j]
		if i != 0:
			i = i - 1
		else:
			j = j - 1
			i = m - 1
if f == 0:
	print(sum1)
else:
	print(-1)


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
(n, m) = mp()
ml = [lmp() for i in range(n)]
sm = 0
flg = True
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 ml[i][j] == 0:
				ml[i][j] = min(ml[i + 1][j], ml[i][j + 1]) - 1
		if i > 0 and j > 0 and (ml[i][j] <= max(ml[i - 1][j], ml[i][j - 1])):
			flg = False
			break
		sm += ml[i][j]
	if not flg:
		break
print(sm if flg else -1)


(n, m) = map(int, input().split())
l = []
for i in range(n):
	l.append(list(map(int, input().split())))
for i in range(m - 1):
	if l[n - 1][i] >= l[n - 1][i + 1] or l[0][i] >= l[0][i + 1]:
		print(-1)
		exit()
for j in range(n - 1):
	if l[j][0] >= l[j + 1][0] or l[j][m - 1] >= l[j + 1][m - 1]:
		print(-1)
		exit()
for j in range(n - 2, -1, -1):
	for i in range(m - 2, -1, -1):
		if l[j][i] == 0:
			low = float('-inf')
			high = float('inf')
			if l[j + 1][i]:
				high = l[j + 1][i]
			if l[j][i + 1] and l[j][i + 1] < high:
				high = l[j][i + 1]
			if l[j - 1][i]:
				low = l[j - 1][i]
			if l[j][i - 1] and l[j][i - 1] > low:
				low = l[j][i - 1]
			if high - 1 <= low:
				print(-1)
				exit()
			else:
				l[j][i] = high - 1
s = 0
for i in l:
	s += sum(i)
print(s)


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)


(n, m) = map(int, input().split())
mat = []
for i in range(n):
	mat.append(list(map(int, input().split())))
c = 0
for x in range(m - 2, 0, -1):
	for y in range(n - 2, 0, -1):
		if mat[y][x] >= mat[y + 1][x] or mat[y][x] >= mat[y][x + 1]:
			print('-1')
			exit(0)
		if mat[y][x] != 0:
			continue
		cand = min(mat[y + 1][x], mat[y][x + 1]) - 1
		if cand <= mat[y - 1][x] or cand <= mat[y][x - 1]:
			print('-1')
			exit(0)
		mat[y][x] = cand
for x in range(m):
	if mat[n - 1][x] <= mat[n - 2][x]:
		print('-1')
		exit(0)
for y in range(n):
	if mat[y][m - 1] <= mat[y][m - 2]:
		print('-1')
		exit(0)
print(sum([sum(x) for x in mat]))


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 readxf():
	text = open('text.txt', 'r')
	(r, c) = text.readline().split()
	file = text.readlines()
	db = []
	for i in file:
		db.append(i.strip().split())
	text.close()
	return (r, c, db)

def readxi():
	text = input()
	(r, c) = text.split(' ')
	i = 0
	db = []
	while i < int(r):
		x = input()
		db.append(x.split())
		i += 1
	return (r, c, db)

def countcheck(r, c, db):
	i = 0
	while i < int(r):
		j = 0
		while j < int(c) - 1:
			if int(db[i][j + 1]) <= int(db[i][j]):
				return -1
			j += 1
		i += 1
	return countcheck2(r, c, db)

def countcheck2(r, c, db):
	i = 0
	while i < int(c) - 1:
		j = 0
		while j < int(r):
			if int(db[i + 1][j]) <= int(db[i][j]):
				return -1
			j += 1
		i += 1
	return sumit(r, c, db)

def sumit(r, c, db):
	i = 0
	count = 0
	while i < int(r):
		j = 0
		while j < int(c):
			count += int(db[i][j])
			j += 1
		i += 1
	return count

def main():
	(r, c, db) = readxi()
	refr = r
	refc = c
	refdb = db
	i = int(r) - 1
	haszero = False
	while i >= 0:
		if '0' in db[i]:
			j = int(c) - 1
			while int(j) >= 0:
				if db[i][j] == '0':
					haszero = True
					two = [int(db[i][j - 1]), int(db[i - 1][j])]
					one = [int(db[i + 1][j]), int(db[i][j + 1])]
					oneval = min(one)
					twoval = max(two)
					eqdown = False
					equp = False
					if max(one) == '0' and min(one) == '0':
						eqdown = True
					elif min(one) == '0':
						oneval = max(one)
					elif max(one) == '0':
						oneval = min(one)
					if max(two) == '0' and min(two) == '0':
						equp = True
					else:
						twoval = max(two)
					if max(two) == min(one):
						db[i][j] = '-1'
					elif int(twoval) == int(oneval) - 1:
						db[i][j] = '-1'
					elif equp == True:
						db[i][j] = int(oneval) - 1
					elif eqdown == True:
						db[i][j] = int(twoval) + 1
					else:
						db[i][j] = int(oneval) - 1
				j -= 1
		else:
			i -= 1
	result = 0
	brk = False
	for r in db:
		if haszero == False:
			result = -1
			break
		for c in r:
			if c == '-1':
				brk = True
				break
			else:
				result += int(c)
		if brk == True:
			result = -1
			break
	if haszero == False:
		result = countcheck(refr, refc, refdb)
	print(result)
main()


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)