#include<bits/stdc++.h>
using namespace std;
const int
N=105,
inf=20000;
int n,m,ans,tag;
int b[N][N],a[N][N],flag[N][N];
bool vis[N][N];
struct node{int high,x,y;};
priority_queue<node>Heap;
bool operator <(node a,node b){return a.high>b.high;}
bool operator >(node a,node b){return a.high<b.high;}
struct QUEUE{int x,y;}Q[N*N];
void BFS(int xstart,int ystart,int num,int f){
int head=0,tail=1;
Q[0]=(QUEUE){xstart,ystart};
flag[xstart][ystart]=tag;
while (head<tail){
int x=Q[head].x,y=Q[head++].y;
if (f) vis[x][y]=1;
if (a[x-1][y]!=num) ans=min(ans,a[x-1][y]);
if (a[x+1][y]!=num) ans=min(ans,a[x+1][y]);
if (a[x][y-1]!=num) ans=min(ans,a[x][y-1]);
if (a[x][y+1]!=num) ans=min(ans,a[x][y+1]);
if (x==1 && num>=0) ans=0;
if (y==1 && num>=0) ans=0;
if (x==n && num>=0) ans=0;
if (y==m && num>=0) ans=0;
if (x>1 && flag[x-1][y]!=tag && a[x-1][y]==num) flag[x-1][y]=tag,Q[tail++]=(QUEUE){x-1,y};
if (x<n && flag[x+1][y]!=tag && a[x+1][y]==num) flag[x+1][y]=tag,Q[tail++]=(QUEUE){x+1,y};
if (y>1 && flag[x][y-1]!=tag && a[x][y-1]==num) flag[x][y-1]=tag,Q[tail++]=(QUEUE){x,y-1};
if (y<m && flag[x][y+1]!=tag && a[x][y+1]==num) flag[x][y+1]=tag,Q[tail++]=(QUEUE){x,y+1};
}
}
void change(int xstart,int ystart,int num,int now){
int head=0,tail=1;
Q[0]=(QUEUE){xstart,ystart};
flag[xstart][ystart]=tag;
while (head<tail){
int x=Q[head].x,y=Q[head++].y;
a[x][y]=now;
if (x>1 && flag[x-1][y]!=tag && a[x-1][y]==num) flag[x-1][y]=tag,Q[tail++]=(QUEUE){x-1,y};
if (x<n && flag[x+1][y]!=tag && a[x+1][y]==num) flag[x+1][y]=tag,Q[tail++]=(QUEUE){x+1,y};
if (y>1 && flag[x][y-1]!=tag && a[x][y-1]==num) flag[x][y-1]=tag,Q[tail++]=(QUEUE){x,y-1};
if (y<m && flag[x][y+1]!=tag && a[x][y+1]==num) flag[x][y+1]=tag,Q[tail++]=(QUEUE){x,y+1};
}
}
void solve(){
while (!Heap.empty()){
node u=Heap.top();Heap.pop();
if (vis[u.x][u.y] || a[u.x][u.y]-b[u.x][u.y]) continue;
ans=inf,tag++;
BFS(u.x,u.y,u.high,0);
if (!ans) tag++,BFS(u.x,u.y,u.high,1);
if (ans<=u.high) continue;
tag++,change(u.x,u.y,u.high,ans);
}
}
int main(){
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
scanf("%d",&a[i][j]),b[i][j]=a[i][j],
Heap.push((node){a[i][j],i,j});
solve();
int answer=0;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++) answer+=max(a[i][j]-b[i][j],0);
printf("%d\n",answer);
return 0;
}