// iostream is too mainstream
#include <cstdio>
// bitch please
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <list>
#include <cmath>
#include <iomanip>
#define dibs reserve
#define OVER9000 1234567890
#define ALL_THE(CAKE,LIE) for(auto LIE =CAKE.begin(); LIE != CAKE.end(); LIE++)
#define tisic 47
#define soclose 1e-8
#define chocolate win
// so much chocolate
#define patkan 9
#define ff first
#define ss second
#define abs(x) ((x < 0)?-(x):x)
#define uint unsigned int
#define dbl long double
using namespace std;
// mylittledoge
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
for(int t =0; t < T; t++) {
int N,G;
cin >> N >> G;
vector< vector<int > > dir(N,vector<int>(4));
for(int i =0; i < N; i++)
for(int j =0; j < 4; j++) {cin >> dir[i][j]; dir[i][j]--;}
vector<int> nxt(4*N,-1);
for(int i =0; i < N; i++) for(int j =0; j < 4; j++) {
for(int k =0; k < 4; k++) if(dir[dir[i][j]][k] == i)
nxt[4*i+j] =4*dir[i][j]+(k+2)%4;
// cout << nxt[4*i+j] << " ";
}
// cout << "\n";
int comp =0;
vector<int> isC(4*N,-1);
for(int i =0; i < 4*N; i++) if(isC[i] == -1) {
int akt =i;
while(isC[akt] == -1) {
isC[akt] =comp;
akt =nxt[akt];}
comp++;}
// for(int i =0; i < N; i++) for(int j =0; j < 4; j++) {
// cout << isC[4*i+j] << " ";}
if(isC[(G-1)*4] == isC[(G-1)*4+1] || isC[(G-1)*4] == isC[(G-1)*4+3])
cout << comp/2-1 << "\n";
else cout << comp/2-2 << "\n";}
return 0;}
// look at my code
// my code is amazing
Ly8gaW9zdHJlYW0gaXMgdG9vIG1haW5zdHJlYW0KI2luY2x1ZGUgPGNzdGRpbz4KLy8gYml0Y2ggcGxlYXNlCiNpbmNsdWRlIDxpb3N0cmVhbT4KI2luY2x1ZGUgPGFsZ29yaXRobT4KI2luY2x1ZGUgPGNzdGRsaWI+CiNpbmNsdWRlID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