#include <iostream>
#include <vector>
struct polje {
	int dolei;
	int dolej;
	int gorei;
	int gorej;
	int status;
	// 0 ne postoji
	// 1 u njemu
	// 2 gotov
	// 3 nevalidan
};
using namespace std;
int main()
{
	vector<polje> polja(1000002);
	for (int i = 0; i < 1000002; i++) polja[i].status = 0;
	int n, recent, x = 1000001, k;
	cin >> n >> k;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++) 
		{
			recent = x;
			cin >> x;
			polje &p = polja[x];
			if (p.status == 0)
			{
				p.dolei = i;
				p.dolej = j;
				p.gorei = i;
				p.gorej = j;
				p.status = 2;
			}
			else if (p.status == 1)
			{
				if (p.gorei == i)
				{
					if (p.gorej == j)
					{
						if (recent == x) {
							p.status = 2;
						}
						else p.status = 3;
					}
					else if (p.gorej < j) {
						if (x != recent) {
							p.status = 3;
						}
					}
					else if (p.gorej > j) {
						p.status = 3;
					}
				}
				else p.status = 3;
			}
			else if (p.status == 2)
			{
				if (p.gorei == i) {
					if (p.gorej + 1 == j && p.dolei == i) {
						p.gorej = j;
					}
					else
					{
						p.status = 3;
					}
				}
				else if (p.gorei + 1 == i && j == p.dolej)
				{
					p.gorei = i;
					if (j != p.gorej) p.status = 1;
				}
				else p.status = 3;
			}

		}
	}
	int	sum = 0;
	for (int i = 0; i < 1000001; i++)
	{
		//cout << i << " " << polja[i].status << endl;
		if (polja[i].status == 2) sum++;
	}
	cout << sum;
	return 0;
}