#include<bits/stdc++.h>
using namespace std;
int a[2005][2005],n,k,br,vel,s,poz,niz[1000005],maxv,siz,newline,zbir,proban,zan[100005];
int pocred,krajred,pocv,krajv,velicina;
vector<int> v[1000000],t;
int prov1;
int prov;
int main()
{
    cin>>n>>k;
    proban=n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>a[i][j];
            if(a[i][j]>maxv){
               maxv=a[i][j];
            }
            poz++;
            v[a[i][j]].push_back(poz);
            if(poz>proban){
               newline++;
               proban+=n;
               zan[newline]=poz;
            }
        }
    }
    for(int x=1;x<=maxv;x++){
        prov1=0;
        vel=0;
        prov=0;
        pocred=1;
        krajred=1;
        //newline=0;
        if(v[x].size()==1){           ///ako je size 1 onda mora biti
           br++;
           continue;
        }
        if(v[x].size()==0){continue;}     ///ako je size 0 ne postoji
        prov1=0;
        for(int i=0;i<v[x].size();i++){
            if(v[x][i+1]-v[x][i]==1){
               vel++;
            }
            else{break;}
        }
        siz=v[x].size();
        for(int i=1;i<=newline;i++){
        if(v[x][0]>=zan[i]){
           pocred++;
        }
        if(v[x][siz-1]>=zan[i]){
           krajred++;
        }
        }
        //cout<<x<<" "<<vel<<" "<<pocred<<" "<<krajred<<endl;
        if(krajred-pocred>=1 and vel>=krajred-pocred){
           if(n*(krajred-pocred)!=v[x].size()){continue;}
        }
        if(krajred-pocred>=1 and vel>=krajred-pocred){
           if(n*(krajred-pocred+1)>v[x].size()){continue;}
        }
        if(vel>=1){
           for(int i=0;i<v[x].size();i++){
               if(v[x][i]+n==v[x][i+vel+1]){
                  prov1++;
               }
           }
        }
        if(prov1==v[x].size()-vel-1){br++;/*cout<<x<<endl;*/continue;}
        prov1=0;
        if(vel==0){
           for(int i=0;i<v[x].size();i++){
               if(v[x][i]+n==v[x][i+1]){
                  prov1++;
               }
           }
        }
        if(prov1==v[x].size()-1){br++;/*cout<<x<<endl;*/continue;}
    }
    cout<<br<<endl;
}