#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <utility>
#include <fstream>
using namespace std;
int nextheight=51;
int N,M;
int grid [20][20];
bool dfs(int i,int j, int prev,bool beenhere[20][20])
{
    if (beenhere[i][j])return true;
    if (i <0 or i>=N or j<0 or j>=M)
    {
        return false;
    }
    else
    {
        if(grid[i][j]>prev)
        {
            nextheight=min(nextheight,grid[i][j]);
            return true;
        }
        else
        {
            beenhere[i][j] = true;
            return (dfs(i+1,j,prev,beenhere)and dfs(i-1,j,prev,beenhere)and dfs(i,j+1,prev,beenhere)and dfs(i,j-1,prev,beenhere));
        }


    }

}
int main()
{
    freopen("DATA5.txt","r",stdin);
    freopen("OUT5.txt","w",stdout);
    for (int asd = 0; asd<5; asd++)
    {
        cin>>N>>M;
        for (int i=0; i<N; i++) //input
            for (int j=0; j<M; j++)
                cin>> grid[i][j];
      /*  cout<<"NEW ";
        cout<<N<<M<<endl;
        for (int i=0; i<N; i++)  //print
        {
            for (int j=0; j<M; j++)
                cout<<grid[i][j];
            cout<<endl;
        }
        cout<<endl;*/

        int total=0;
        int small = 0;
        //repeat
        while(true)
        {
            //cout<<"small "<<small<<endl;
            vector < pair <int,int> > q;
            nextheight = 51;
            // finding the smallest
            for (int i=0; i<N; i++)
                for (int j=0; j<M; j++)
                {
                    if (grid[i][j]==small)
                    {
                        q.push_back(make_pair(i,j));
                    }
                }

            if (small >=51)break;
            for (int i = 0; i<q.size(); i++)
            {

                pair<int,int> cur = q.at(i);
                /*for (int i=0; i<N; i++)  //print
                {
                    for (int j=0; j<M; j++)
                        cout<<grid[i][j];
                    cout<<endl;
                }
                cout<<endl;*/
               /* cout<<"here ";
                cout<<cur.first<< " "<<cur.second<<" "<< grid[cur.first][cur.second]<< " ";
                cout<<( dfs(cur.first, cur.second, grid[cur.first][cur.second]))<<endl;*/
                bool beenhere[20][20]={0};
                if (dfs(cur.first, cur.second, grid[cur.first][cur.second],beenhere))
                {
                    total+=(nextheight-grid[cur.first][cur.second]);
                    grid[cur.first][cur.second]=nextheight;
                }
            }
            small+=1;

        }
        //  cout<<"here";
        cout<<total<<endl;

    }
}

