#ifdef SU1
#define _GLIBCXX_DEBUG
#endif

#include <algorithm>
#include <bitset>
#include <cassert>
#include <climits>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <stack>
#include <set>
#include <string>
#include <utility>
#include <vector>

using namespace std;

#define forn(i, n) for (int i = 0; i < int(n); i++)
#define forl(i, n) for (int i = 1; i <= int(n); i++)
#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)
#define fore(i, l, r) for (int i = int(l); i <= int(r); i++)
#define pb(a) push_back(a)
#define mp(x, y) make_pair((x), (y))
#define sz(a) (int) (a).size()
#define all(a) (a).begin(), (a).end()
#define ft first
#define sc second
#define x first
#define y second

template<typename X> inline X abs(const X& a) { return a < 0 ? -a : a; }
template<typename X> inline X sqr(const X& a) { return a * a; }

typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;

const int INF = int(1e9);
const li INF64 = li(1e18);
const ld PI = acosl(ld(-1));
const ld EPS = 1e-9;

const int N = 100500;
int n;
int g;
int nx[N][4];

inline bool read()
{
	assert(scanf("%d%d", &n, &g) == 2);
	g--;
	forn(i, n) {
		forn(j, 4) {
			assert(scanf("%d", &nx[i][j]) == 1);
			nx[i][j]--;
		}
	}
	return true;
}

int used[N][4], cused;

inline void solve()
{
	int cnt = 0;
	cused++;
	forn(i, n) {
		forn(j, 4) {
			if (used[i][j] == cused)
				continue;
			pt cur(i, j);
			bool good = true;
//			cerr << "==----" << endl;
			while (used[cur.x][cur.y] != cused) {
//				cerr << cur.x + 1 << ' ' << nx[cur.x][cur.y] + 1 << endl;
				used[cur.x][cur.y] = cused;
				if (cur.x == g) good = false;
				pt to;
				to.x = nx[cur.x][cur.y];
				forn(t, 4) {
					if (nx[to.x][t] == cur.x) {
						to.y = (t + 2) % 4;
					}
				}
				cur = to;
			}
			if (good) cnt++;
		}
	}
	assert(cnt % 2 == 0);
	printf("%d\n", cnt / 2);
}

int main()
{
#ifdef SU1
	assert(freopen("input.txt", "rt", stdin));
//	assert(freopen("output.txt", "wt", stdout));
#endif

	cout << fixed << setprecision(10);
	cerr << fixed << setprecision(5);

	int T;
	assert(scanf("%d", &T) == 1);
	forn(i, T) {
		assert(read());
		solve();
	}
	
#ifdef SU1
	cerr << "=== TIME : " << clock() << " ===" << endl;
#endif
	return 0;
}
