#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define f first
#define s second
#define ll long long
#define llu unsigned long long
#define pb push_back

using namespace std;

int leftt[1000002],rightt[1000002],roww[1000002],visited[1000002],row2[1000002];
int mat[2002][2002];

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    cout.tie(NULL);

	int n,k;
	cin >> n >> k;
	int prev,cnt=0;

	for(int i = 1;i<=n;i++){
        prev=0;
        for(int j = 1;j<=n;j++){
            cin >> mat[i][j];

            if(visited[mat[i][j]]){
                prev=mat[i][j];
                continue;
            }

            if(prev!=mat[i][j]){

                if(roww[prev]>1 && rightt[prev]!=j-1){
                    visited[prev]=true;
                }

                if(leftt[mat[i][j]]==0){
                    cnt++;
                    leftt[mat[i][j]]=j;
                    rightt[mat[i][j]]=j;
                    roww[mat[i][j]]=1;
                    row2[mat[i][j]]=i;
                }
                else if(leftt[mat[i][j]]==j){
                    roww[mat[i][j]]=2;
                    if(i!=row2[mat[i][j]]+1){
                        if(!visited[mat[i][j]]){
                            visited[mat[i][j]] = true;
                            cnt--;
                        }
                    }
                    row2[mat[i][j]]++;

                }
                else if(!visited[mat[i][j]]){
                    visited[mat[i][j]] = true;
                    cnt--;
                }
            }
            else{
                if(rightt[mat[i][j]]<j){
                    if(roww[mat[i][j]]==2){
                        if(!visited[mat[i][j]]){
                            visited[mat[i][j]] = true;
                            cnt--;
                        }
                    }
                    else{
                        rightt[mat[i][j]]=j;
                    }
                }
            }

            //cout << prev << " " << leftt[mat[i][j]] << " " << rightt[mat[i][j]] << " " << visited[mat[i][j]] << " " << roww[mat[i][j]] << " " << i << " " << j << endl;
            prev=mat[i][j];
        }
	}

	cout << cnt;

	/*for(int i = 1;i<=k;i++){
        if(visited[k]){
            cout << i;
        }
	}*/

    return 0;
}