#include <bits/stdc++.h>

typedef unsigned long long __uint64;

using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cerr.tie(0);

    int n, b;
    int c = 0;
    int cval = 0;
    cin >> n >> b;

    int **g = (int**)malloc(n * sizeof(int*));
    for(int i = 0; i < n; i++)
        g[i] = (int*)malloc(n * sizeof(int));

    bool *done = (bool*)calloc(b + 1, sizeof(bool));
    bool *dq = (bool*)calloc(b + 1, sizeof(bool));

    for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
            cin >> g[i][j];

    int **nums = (int**)malloc((b + 1) * sizeof(int*));
    for(int i = 0; i <= b; i++)
        nums[i] = (int*)calloc(4, sizeof(int));

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            if(g[i][j] != cval)
            {
                cval = g[i][j];
                if((done[cval] || dq[cval]) && (i < nums[cval][0] || j < nums[cval][1] || i > nums[cval][2] || j > nums[cval][3]))
                {
                    done[cval] = false;
                    dq[cval] = true;
                    continue;
                }
                int ii = j;
                nums[cval][0] = i;
                nums[cval][1] = j;
                while(ii < n && g[i][ii] == cval)
                    ii++;
                ii--;
                int jj = ii;
                nums[cval][3] = ii;
                ii = i;
                while(ii < n && g[ii][jj] == cval)
                    ii++;
                ii--;
                nums[cval][2] = ii;
                if(!dq[cval])
                    done[cval] = true;
            }
            else if(g[i][j] == cval && (i < nums[cval][0] || j < nums[cval][1] || i > nums[cval][2] || j > nums[cval][3]))
            {
                done[cval] = false;
                dq[cval] = true;
            }
        }
    }

    for(int i = 0; i <= b; i++)
        if(done[i])
            c++;

    cout << c;

    return 0;
}