#include <bits/stdc++.h>
using namespace std;

int n,k,rs=0;

int main()
{
    scanf("%d%d",&n,&k);
    int a[n][n];
    int c[k+1]={0};
    bool upBlock[k+1]={false},downBlock[k+1]={false};
    for(int x=0;x<n;x++)
    {
        for(int y=0;y<n;y++)
        {
            scanf("%d",&a[x][y]);
            c[a[x][y]]++;
        }
    }
    for(int x=0;x<n;x++)
    {
        for(int y=0;y<n;y++)
        {
            //cout << "Trenutno na poziciji x: " << x << " y: " << y << endl;
            //cout << "Vertikalno: " << endl;
            if(y!=n-1 && a[x][y]==a[x][y+1] && upBlock[a[x][y]]==false)
            {
                //cout << "Poklapanje broja na mestu: " << x << " " << y << " i broja na mestu: " << x << " " << y+1 << endl;
                c[a[x][y]]--;
            }
            else if(upBlock[a[x][y]]==false)
            {
                //cout << "Broj " << a[x][y] << " vise nije validan vertikalno" << endl;
                upBlock[a[x][y]]=true;
            }
            //cout << "Horizontalno: " << endl;
            if(x!=n-1 && a[x][y]==a[x+1][y] && downBlock[a[x][y]]==false)
            {
                //cout << "Poklapanje broja na mestu: " << x << " " << y << " i broja na mestu: " << x+1 << " " << y << endl;
                c[a[x][y]]--;
            }
            else if(downBlock[a[x][y]]==false)
            {
                //cout << "Broj " << a[x][y] << " vise nije validan horizontalno" << endl;
                downBlock[a[x][y]]==true;
            }

            if(c[a[x][y]]==1)
            {
                //cout << "Broj: " << a[x][y] << " gradi pravougaonik +++++++++///+++++++++" << endl;
                rs++;
                c[a[x][y]]=0;
            }
        }
    }
    printf("%d",rs);
}