#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <queue>
#define pb push_back
#define rep(i,a,b) for (int i = (a);i<(b);i++)
using namespace std;
typedef long long ll;
const int maxh = 1e6 + 3;
const int maxn = 1e3 + 3;
struct TCell
{
int x,y,val;
TCell() : x(0),y(0),val(0) {};
TCell(int x_,int y_,int val_) : x(x_),y(y_),val(val_) {};
};
struct cmp
{
bool operator() (const TCell &a,const TCell &b)
{
return a.val > b.val;
}
};
int a[maxn][maxn],h[maxn][maxn];
priority_queue<TCell,vector<TCell>,cmp> q;
int m,n;
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};
bool inside(int x,int y)
{
return !(x == m || y == n || x == 0-1 || y == 0-1);
}
void dijkstra()
{
rep(i,0,m) rep(j,0,n) h[i][j] = maxh;
rep(i,0,m)
{
h[i][0] = a[i][0];
h[i][n-1] = a[i][n-1];
q.push(TCell(i,0,h[i][0]));
q.push(TCell(i,n-1,h[i][n-1]));
}
rep(i,1,n-1)
{
h[0][i] = a[0][i];
h[m-1][i] = a[m-1][i];
q.push(TCell(0,i,a[0][i]));
q.push(TCell(m-1,i,a[m-1][i]));
}
while (! q.empty())
{
int x = q.top().x;
int y = q.top().y;
int d = q.top().val;
q.pop();
if (h[x][y] != d) continue;
rep(i,0,4)
{
int xk = x+dx[i];
int yk = y+dy[i];
if (inside(xk,yk))
{
int nprio = max(a[xk][yk],d);
if (h[xk][yk] > nprio)
{
h[xk][yk] = nprio;
q.push(TCell(xk,yk,nprio));
}
}
}
}
}
int main()
{
scanf("%d%d",&m,&n);
rep(i,0,m) rep(j,0,n) scanf("%d",&a[i][j]);
dijkstra();
ll ans = 0;
rep(i,0,m) rep(j,0,n) ans += h[i][j] - a[i][j];
printf("%lld",ans);
return 0;
}
I2luY2x1ZGUgPGNzdGRpbz4KI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8Y3N0cmluZz4KI2luY2x1ZGUgPHF1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LG4tMSxoW2ldW24tMV0pKTsKICAgIH0gCiAgICByZXAoaSwxLG4tMSkgCiAgICB7CiAgICAgICAgaFswXVtpXSA9IGFbMF1baV07CiAgICAgICAgaFttLTFdW2ldID0gYVttLTFdW2ldOwogICAgICAgIHEucHVzaChUQ2VsbCgwLGksYVswXVtpXSkpOwogICAgICAgIHEucHVzaChUQ2VsbChtLTEsaSxhW20tMV1baV0pKTsKICAgIH0KICAgIHdoaWxlICghIHEuZW1wdHkoKSkKICAgIHsKICAgICAgICBpbnQgeCA9IHEudG9wKCkueDsKICAgICAgICBpbnQgeSA9IHEudG9wKCkueTsKICAgICAgICBpbnQgZCA9IHEudG9wKCkudmFsOwogICAgICAgIHEucG9wKCk7CiAgICAgICAgaWYgKGhbeF1beV0gIT0gZCkgY29udGludWU7CiAgICAgICAgcmVwKGksMCw0KQogICAgICAgIHsKICAgICAgICAgICAgaW50IHhrID0geCtkeFtpXTsKICAgICAgICAgICAgaW50IHlrID0geStkeVtpXTsKICAgICAgICAgICAgaWYgKGluc2lkZSh4ayx5aykpCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgIGludCBucHJpbyA9IG1heChhW3hrXVt5a10sZCk7CiAgICAgICAgICAgICAgICBpZiAoaFt4a11beWtdID4gbnByaW8pCiAgICAgICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAgICAgaFt4a11beWtdID0gbnByaW87CiAgICAgICAgICAgICAgICAgICAgcS5wdXNoKFRDZWxsKHhrLHlrLG5wcmlvKSk7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICB9Cn0KIAppbnQgbWFpbigpCnsKICAgIHNjYW5mKCIlZCVkIiwmbSwmbik7CiAgICByZXAoaSwwLG0pIHJlcChqLDAsbikgc2NhbmYoIiVkIiwmYVtpXVtqXSk7CiAgICBkaWprc3RyYSgpOwogICAgbGwgYW5zID0gMDsKICAgIHJlcChpLDAsbSkgcmVwKGosMCxuKSBhbnMgKz0gaFtpXVtqXSAtIGFbaV1bal07CiAgICBwcmludGYoIiVsbGQiLGFucyk7CiAgICByZXR1cm4gMDsKfSA=