#include<iostream>
using namespace std;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int koriscen[2001][2001], m[2001][2001], rez, ktip[1000001];
int n, k;
int maxx, maxy, minx, miny;
void dfs(int x, int y){

    koriscen[x][y] = true;
    maxx = max(x, maxx);
    maxy = max(y, maxy);
    minx = min(x, minx);
    miny = min(y, miny);

    for(int i = 0; i < 4; i++){
        int x1 = x + dx[i];
        int y1 = y + dy[i];
        if(!koriscen[x1][y1] and m[x1][y1] == m[x][y] and x1 >= 1 and x1 <= n and y1 >= 1 and y1 <= n){
            dfs(x1, y1);
        }
    }
}
int main(){

    cin >> n >> k;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            cin >> m[i][j];

    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            if(!koriscen[i][j])
                if(ktip[m[i][j]] == 1 or ktip[m[i][j]] == -1){
                    ktip[m[i][j]] = -1;
                }
                    else {
                        maxx = maxy = 0;
                        minx = miny = 2010;
                        dfs(i, j);

                        bool dobar = true;
                        for(int k = minx; k <= maxx; k++){
                            for(int l = miny; l <= maxy; l++)
                                if(m[i][j] != m[k][l]){
                                        if(m[k][l] == 2){
                                        //    cout << "kec\n";
                                       //     cout << "i = " << i << " j = " << j << " k = " << k << " l = " << l << endl;
                                       //     cout << "maxx = " << maxx << " minx = " << minx << " maxy = " << maxy << " miny = " << miny << endl;
                                        }
                                       // if(m[i][j] == 2)
                                        //    cout << "dvica\n";

                                        ktip[m[i][j]] = -1;
                                        dobar = false;
                                        break;
                                }
                            if(!dobar)
                                break;
                        }
                        if(dobar)
                            ktip[m[i][j]] = 1;
                    }

    for(int i = 1; i <= k; i++)
        if(ktip[i] == 1){
            rez++;
            //cout  << "dobar " << i << endl;
        }

    cout << rez;

    return 0;
}