#include <iostream>

using namespace std;
int domen[1000000][2];
bool bio[1000000]={false};
int gotov[1000000]={0};
int red[1000000];
int main()
{
   int n, k;
   cin>>n>>k;
   int niz[2000];
   for(int i=0; i<n; i++)
   {
       for(int j=0; j<n; j++)
       {
          cin>>niz[j];
          if(bio[niz[j]]==false)
          {
              gotov[niz[j]]=2;
          }
          if(j>0 && niz[j]!=niz[j-1] && domen[niz[j-1]][1]==-1)
          {
              domen[niz[j-1]][1]=j-1;
          }
          else if(j>0 && niz[j]!=niz[j-1] && domen[niz[j-1]][1]>=j)
          {
              gotov[niz[j-1]]=1;
              //cout<<niz[j-1]<<" neko u d"<<endl;
          }
          if(bio[niz[j]]==false)
          {
            bio[niz[j]]=true;
            domen[niz[j]][0]=j;
            domen[niz[j]][1]=-1;
            if(j==n-1)
            {
               domen[niz[j]][1]=j;
            }
            red[niz[j]]=i;
          }
          else if(bio[niz[j]]==true && domen[niz[j]][1]>-1)
          {
            if(j<domen[niz[j]][0] || j>domen[niz[j]][1] || i-1!=red[niz[j]])
            {
                    gotov[niz[j]]=1;
                    //cout<<j<<" van domena"<<endl;
            }
            if(j==domen[niz[j]][1] && red[niz[j]]==i-1 && gotov[niz[j]]==2)
            {
                for(int a=j; a>=domen[niz[j]][0]; a--)
                {
                    if(niz[a]!=niz[j])
                    {
                        gotov[niz[j]]=1;
                        //cout<<niz[j]<<" manji od kraja d"<<endl;
                    }

                }
                 if(gotov[niz[j]]==2)
                 {
                        red[niz[j]]=i;
                 }
            }
          }
          if(j==n-1 && niz[j]==niz[j-1] && domen[niz[j-1]][1]==-1)
          {
              domen[niz[j-1]][1]=j;
          }

       }
   }
   int zbir=0;
   for(int i=0; i<=k; i++)
   {
       //cout<<gotov[i]<<" "<<i<<endl;
       if(gotov[i]==2){
         zbir++;
       }

   }
   cout<<zbir;
    return 0;
}