#include <bits/stdc++.h>
using namespace std;

int farm[2000][2000];
int n, k;

int main()
{
	cin >> n >> k;
	for (int i=0; i<n; ++i) { for (int j=0; j<n; ++j) cin >> farm[i][j]; }
	map<int, bool> used;
	map<int, bool> res;
	map<int, bool> banned;
	for (int i=0; i<n; ++i)
	{
		map<int, bool> just_added;
		for (int j=0; j<n; ++j)
		{
			if (i==0)
			{
				if (used[farm[0][j]] && farm[0][j-1]!=farm[0][j]) { res[farm[0][j]] = 0; banned[farm[0][j]] = 1; }
				if (!used[farm[0][j]] && !banned[farm[0][j]]) { used[farm[0][j]] = 1; res[farm[0][j]] = 1; }
			}
			else
			{
				if (used[farm[i][j]] && farm[i-1][j]!=farm[i][j] && !just_added[farm[i][j]] 								//not vertically adjacent
				|| 	(just_added[farm[i][j]] && farm[i][j-1]!=farm[i][j])) { res[farm[i][j]] = 0; banned[farm[i][j]] = 1; }	//not horizontally adjacent
				if (!used[farm[i][j]] && !banned[farm[i][j]]) {used[farm[i][j]] = 1; res[farm[i][j]] = 1; just_added[farm[i][j]]=1;}
			}
		}
	}
	int sol = 0;
	for (int i = 1; i <= k; ++i) { if (res[i])++sol; }
	cout << sol << '\n';
}