def rotate(a, n, m):
res = []
for i in range(m):
res.append([])
for j in range(n):
res[i].append(a[j][m - 1 - i])
return res
n, m = input().split()
n = int(n)
m = int(m)
a = [[int(x) for x in input().split()] for i in range(n)]
ans = []
for i in range(n):
ans.append([])
for j in range(m):
ans[i].append(0)
for rotation in range(4):
mx = []
for i in range(n):
mx.append([])
for j in range(m):
mx[i].append(a[i][j] + i + j)
if i != 0:
mx[i][j] = max(mx[i][j], mx[i - 1][j])
if j != 0:
mx[i][j] = max(mx[i][j], mx[i][j - 1])
ans[i][j] = max(ans[i][j], mx[i][j] - i - j)
ans = rotate(ans, n, m)
a = rotate(a, n, m)
n, m = m, n
res = ans[0][0]
for i in range(n):
for j in range(m):
res = min(res, ans[i][j])
print(res)