#include <bits/stdc++.h>
#define KMAX 1000008
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<ll> vll;
#define forn(a,b,c) for(int a=b;a<c;a++)
#define ford(a,b,c) for(int a=b;a>=c;a--)
int n,k, ans = 0;
vector<vector<ii>> M;
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin >> n >> k;
    M.assign(k, vector<ii>());
    forn(i,0,n)
    {
        forn(j,0,n)
        {
            int r;
            cin >> r;
            r--;
            M[r].push_back(make_pair(i,j));
        }
    }
    forn(i,0,k)
    {
        bool b = true;
        ii p1;
        if(!M[i].empty())
            p1 = M[i][0];
        else
            b = false;
        int red = p1.first;
        int mn = p1.second;
        int mx = p1.second;
        int vel = (int)M[i].size();
        forn(j,1,vel)
        {
            ii p2 = M[i][j];
            if(p1.first == p2.first)
            {
                if(p1.second + 1 != p2.second)
                {
                    b = false;
                    break;
                }
                else if(p1.first == red)
                    mx++;
                else if(p2.second > mx)
                {
                    b = false;
                    break;
                }
            }
            else if(p1.first + 1 == p2.first)
            {
                if(p1.second != mx)
                {
                    b = false;
                    break;
                }
                if(p2.second != mn)
                {
                    b = false;
                    break;
                }
            }
            else
            {
                b = false;
                break;
            }
            if(j == vel - 1)
            {
                if(p2.second != mx)
                {
                    b = false;
                    break;
                }
            }
            p1 = p2;
        }
        if(b)
            ans++;
    }
    cout << ans;
    return 0;
}