#include <iostream>
#include <vector>

using namespace std;

struct cord {
	int row, col;
	cord(int i, int j) {
		row = i; col = j;
	}
};

bool checkNum(vector<cord>& arr) {

	// kraj je duzina

	int red = arr[0].row;
	int poc = arr[0].col;
	int kraj;
	bool cont = false;
	int i;
	for (i = 1; i < arr.size(); i++) {
		if (arr[i].row - red == 0 && arr[i].col - arr[i - 1].col == 1) {
			/*if (arr[i].row - red == 1) {
				kraj = i;
				cont = true;
				break;
			}*/
			continue;
		}
		else if (arr[i].row - arr[i - 1].row == 1 && arr[i].row - 1 == red && arr[i - 1].col && arr[i].col == poc) {
			kraj = i;
			break;
		}
		else {
			return false;
		}
	}
	if (!cont) {
		return true;
	}
	if (arr.size() % kraj>0) {
		return false;
	}

	//uporedi za ostale
	for (i; i < arr.size();i++) {
		if (arr[i].row - red == 0 && arr[i].col - arr[i - 1].col == 1) {
			continue;
		}
		else if (arr[i].row - arr[i - 1].row == 1 && arr[i].row - 1 == red && arr[i - 1].col == arr[kraj-1].col && arr[i].col == poc) {
			red++;
		}
		else {
			break;
		}
		
	}
	if (i != arr.size()) {
		return false;
	}
	else {
		return true;
	}
}

int main() {
	int n, k;
	cin >> n >> k;
	vector<vector<int>> mat(n);
	for (int i = 0; i < n; i++) {
		mat[i].resize(n);
	}

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

	vector<vector<cord>> arr(k+1);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			arr[mat[i][j]].push_back({ i,j });
		}
	}

	int res = 0;
	for (int i = 1; i <= k; i++) {
		if (arr[i].size() != 0) {
 			if (checkNum(arr[i])) {
				res++;
			}
		}
	}
	cout << res;

}