#include <stdio.h>

typedef enum
{
	notFound = 0,
	pogodno,
	notPogodno
} state;

int m[2000][2000];
state foundSorts[1000001];

int main()
{
	int n, k;


	scanf("%d%d", &n, &k);
	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			scanf("%d", &m[i][j]);
		}
	}

	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			if (m[i][j] != 0)
			{
				register int zone = m[i][j];
				if (foundSorts[m[i][j]] == notFound)
				{
					int width;
					for (width = j; m[i][width] == zone && j < n; ++width)
						;
					--width;
					for (int k = i; m[k][j] == zone && k < n; ++k)
					{
						register int l;
						for (l = j; m[k][l] == zone && l < n; ++l)
							m[k][l] = 0;
						if (--l != width)
						{
							foundSorts[zone] = notPogodno;
							break;
						}
					}
					if (foundSorts[zone] != notPogodno)
					{
						foundSorts[zone] = pogodno;
					}
				}
				else if (foundSorts[zone] == pogodno)
				{
					foundSorts[zone] = notPogodno;
				}
			}
		}
	}
	int result = 0;
	for (int i = 0; i < k; ++i)
	{
		if (foundSorts[i] == pogodno)
		{
			++result;
		}
	}

	printf("%d\n", result);

	return 0;
}