#include <bits/stdc++.h>

using namespace std;

int a[2013][2013];
pair<int, int> mark[1000013];

int main()
{
	int n, k;
	cin >> n >> k; int sol = k;
	for(int i=1; i<=n; i++)
		for(int j=1; j<=n; j++)
			cin >> a[i][j];
	for(int i=1; i<=n; i++)
		for(int j=1; j<=n; j++)
		{
			int sort = a[i][j];
			if(!(mark[sort].first)) mark[sort] = {i, j};
			else
			{
				bool dec = false;
				if(mark[sort].first  < i) dec = dec || (a[i-1][j] != sort);
				if(mark[sort].second < j) dec = dec || (a[i][j-1] != sort);
				sol -= !!dec;
			}
		}
	cout << sol << endl;
	return 0;
}