def bfs():
global q,a,n,m,s,b
x=int(0)
y=int(0)
q.append([0,0])
b[0][0]=1
c=int(0)
j=int(0)
while len(q)!=0:
#print(j)
x=q[0][0]
y=q[0][1]
if x+1==n and y+1==m:
return
# for i in range(len(q)):
# if q[i]//1000==n-1 and q[i]%1000==m-1:
# print(q)
# return
del q[0]
b[x][y]=1
if x!=0 and b[x-1][y]==0 and abs(a[x][y]-a[x-1][y])<2:
u=[x-1,y]
q.append(u)
#print("n")
if y!=0 and b[x][y-1]==0 and abs(a[x][y]-a[x][y-1])<2:
u = [x, y-1]
q.append(u)
#print("w")
if x!=n-1 and b[x+1][y]==0 and abs(a[x][y]-a[x+1][y])<2:
u = [x+1, y]
q.append(u)
#print('s')
if y!=m-1 and b[x][y+1]==0 and abs(a[x][y]-a[x][y+1])<2:
u = [x, y+1]
q.append(u)
#print("e")
if j==c:
s=s+1
c=c+len(q)
#print("next",s,sep=' ')
#print(q)
j=j+1
s=-1
return
q=[]
a=[]
b=[]
s=int(0)
n,m=map(int,input().split())
for i in range(n):
w=[0 for j in range(m)]
b.append(w)
for i in range(n):
t=list(map(int,input().split()))
a.append(t)
bfs()
print(s+1)