#include <bits/stdc++.h>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    uint32_t K;
    uint16_t N;
    
    cin >> N >> K;
    
    unordered_set<uint32_t> which, wrong;
    which.reserve(K);
    wrong.reserve(K);
    
    uint32_t a[N][N];

    for(uint16_t i = 0; i < N; i++){
        for(uint16_t j = 0; j < N; j++){
            cin >> a[i][j];
        }
    }
    
    for(uint16_t i = 0; i < N; i++){
        for(uint16_t j = 0; j < N; j++){
            if(which.find(a[i][j]) == which.end()){
                which.insert(a[i][j]);
                continue;
            }
            if(a[i][j] == a[i][j - 1] && j > 0){
                if(a[i][j] == a[i - 1][j] && i > 0){
                    if(a[i][j] != a[i - 1][j - 1] && i > 0 && j > 0) wrong.insert(a[i][j]);
                }else if(a[i][j] == a[i - 1][j - 1] && i > 0 && j > 0) wrong.insert(a[i][j]);
            }else if(a[i][j] == a[i - 1][j - 1] && i > 0 && j > 0) wrong.insert(a[i][j]);
            else if(a[i][j] != a[i - 1][j] && i > 0) wrong.insert(a[i][j]);
        }
    }
    
    cout << which.size() - wrong.size();
}