public static void main(String[] args) throws Throwable{
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (int i = 0, N = parseInt(in.readLine().trim()); i < N; i++) {
            in.readLine();
            StringTokenizer st = new StringTokenizer(in.readLine().trim());
            arr = new int[parseInt(st.nextToken())][parseInt(st.nextToken())];
            camino = new boolean[arr.length][arr[0].length];
            for (int j = 0; j < arr.length; j++) {
                st = new StringTokenizer(in.readLine().trim());
                int I = parseInt(st.nextToken());
                while(st.hasMoreTokens())
                    camino[I - 1][parseInt(st.nextToken()) - 1]=true;
            }
            for (int j = 0; j < arr.length; j++) Arrays.fill(arr[j], MAX_VALUE - 1);
            arr[0][0] = 0;
            if(!camino[0][1]){
                cambio = new boolean[arr.length][arr[0].length];
                cambio[0][0]=true;
                hallarCamino(0, 1);
            }
            else if(!camino[1][0]){
                cambio = new boolean[arr.length][arr[0].length];
                cambio[0][0]=true;
                hallarCamino(1, 0);
            }
            if(arr[arr.length-1][arr[0].length - 1]==MAX_VALUE||arr[arr.length-1][arr[0].length - 1]==MAX_VALUE-1)System.out.println(0);
            else System.out.println(caminos(arr.length-1, arr[0].length - 1));
            if(i<N-1)System.out.println();
        }
    }