#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;

int T;
int n;
int ans;
const int N = (int)1e5 + 100;
int g[N][5];
bool used[N][5];
int p;
bool visited;

void dfs(int v, int dir)
{
	while(!used[v][dir])
	{
		used[v][dir] = 1;
		if (v == p) visited = 1;
		int to = g[v][dir];
		dir = 0;
		while (g[to][dir] != v) dir++;
		used[to][dir] = 1;
		if (dir < 2)
			dir += 2;
		else
			dir -= 2;
		v = to;
	}
	return;
}

void solve()
{
	ans = 0;
	scanf("%d%d", &n, &p);
	p--;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			scanf("%d", &g[i][j]);
			g[i][j]--;
			used[i][j] = 0;
		}
	}
	for (int i = 0; i < n; i++)
		for (int j = 0; j < 4; j++)
		{
			if (!used[i][j])
			{
				visited = 0;
				dfs(i, j);
				if (!visited) ans++;
			}
		}
	printf("%d\n", ans);
	return;
}

int main()
{
	
//	freopen("input.txt", "r", stdin);
//	freopen("output.txt", "w", stdout);

	scanf("%d", &T);
	while(T--)
		solve();

	return 0;
}