n,m=map(int,input().split())
L=[[int(x) for x in input().split()]for _ in range(n)]
answer=1000000
a=0
b=0
for i in range(n): #尋找起始點
for j in range(m):
if L[i][j]<answer:
answer=L[i][j]
a=i
b=j
L[a][b]=1000000
while True: #重複直到無路可走
ta=-1
tb=-1
temp=1000000
flag2=True
if a+1<n:
if L[a+1][b]<temp:
ta=a+1
tb=b
temp=L[a+1][b]
flag2=False
if a-1>=0:
if L[a-1][b]<temp:
ta=a-1
tb=b
temp=L[a-1][b]
flag2=False
if b+1<m:
if L[a][b+1]<temp:
ta=a
tb=b+1
temp=L[a][b+1]
flag2=False
if b-1>=0:
if L[a][b-1]<temp:
ta=a
tb=b-1
temp=L[a][b-1]
flag2=False
if not flag2:
answer+=L[ta][tb]
L[ta][tb]=1000000 # 走過的路放置極大數防止重複拜訪
a=ta
b=tb
else:
break
print(answer)