#include <bits/stdc++.h>
using namespace std;
struct Rect{
int xmax,ymax,xmin,ymin;

};
int counter=0;
Rect Def(){

Rect x;
x.xmax=-1;
x.ymax=-1;
x.xmin=10000000;
x.ymin=10000000;
return x;
}
//vector<vector <bool> > Bio;
char Unique[1000000];
int a[2000][2000];
Rect  Rects[1000000];
int   Count[1000000];
int n,k;
int i,j;
int rez=0;
int P=0;
void DFS(int x,int y,int color){

stack<pair<int,pair<int,int> > > Helper;
Helper.push(make_pair(color,make_pair(x,y)));
while(Helper.size()){
         counter++;
color=Helper.top().first;
x=Helper.top().second.first;
y=Helper.top().second.second;
Helper.pop();
if(x<0||y<0||x>=n||y>=n)continue;
if(a[x][y]!=color)continue;
Rects[color].xmax=max(x,Rects[color].xmax);
Rects[color].ymax=max(y,Rects[color].ymax);
Rects[color].xmin=min(x,Rects[color].xmin);
Rects[color].ymin=min(y,Rects[color].ymin);
a[x][y]=-1;

Helper.push(make_pair(color,make_pair(x+1,y)));
Helper.push(make_pair(color,make_pair(x-1,y)));
Helper.push(make_pair(color,make_pair(x,y+1)));
Helper.push(make_pair(color,make_pair(x,y-1)));
}
}
int main(){

cin >>n>>k;

//vector <int> vi(n);
//a.resize(n,vi);

//vector <bool> vb(n,0);
//Bio.resize(n,vb);
//Unique.resize(k,0);
//Rects.resize(k,Def());

//Count.resize(k);
for(i=0;i<k;i++){
    Rects[i]=Def();
}
for(i=0;i<n;i++){
    for(j=0;j<n;j++){
        cin >>a[i][j];
      //  a[i][j]=1;
        a[i][j]--;
        Count[a[i][j]]++;

    }
}//cout <<"NIJE PUKLOO"<<endl;

for( i=0;i<n;i++){
    for( j=0;j<n;j++){

            if(a[i][j]!=-1&&Unique[a[i][j]]==0){
                     Unique[a[i][j]]=1;
                DFS(i,j,a[i][j]);

            }

        else if(a[i][j]!=-1){
    Unique[a[i][j]]=-1;
   // cout<<"OU"<<endl;
   }


    }
}

for( i=0;i<k;i++){

if(Unique[i]==-1)continue;
if(Unique[i]==0){//cout <<"000000 "<<i<<endl;
    continue;}

P=(Rects[i].xmax-Rects[i].xmin+1)*(Rects[i].ymax-Rects[i].ymin+1);
//cout <<P<<endl;

if(P==Count[i])rez++;
}
cout <<rez<<endl;

}