// Arup Guha
// 2/18/2205
// Solution to Final Individual Contest Problem A: Almost Magic Square

import java.util.*;

public class almost {

	// Groups to look at.
	final public static int[][] IDX = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};

	public static int d;
	public static int[] nums;

	public static void main(String[] args) {
	
		Scanner stdin = new Scanner(System.in);
		int nC = stdin.nextInt();
		
		// Process cases.
		for (int loop=0; loop<nC; loop++) {
		
			// Get input.
			d = stdin.nextInt();
			nums = new int[9];
			for (int i=0; i<9; i++)
				nums[i] = stdin.nextInt();
				
			// Solve it!
			System.out.println(go(new int[9], new boolean[9], 0));
		}
	}
	
	// Returns the answer for the first k items of perm being fixed.
	public static int go(int[] perm, boolean[] used, int k) {
	
		// Done filling it in, evalulate.
		if (k == perm.length) return eval(perm);
		
		// Try each item in slot k, adding up the results.
		int res = 0;
		for (int i=0; i<perm.length; i++) {
			if (used[i]) continue;
			used[i] = true;
			perm[k] = i;
			res += go(perm, used, k+1);
			used[i] = false;
		}
		
		// Ta da!
		return res;
	}
	
	// Evaluates this permutation.
	public static int eval(int[] perm) {
		
		// Initial values should be good enough.
		int low = 1000000000, high = 0;
		
		// Try each group.
		for (int i=0; i<IDX.length; i++) {
			
			// Add values in this row, col or diagonal.
			int tmp = 0;
			for (int j=0; j<IDX[i].length; j++)
				tmp += nums[perm[IDX[i][j]]];
			
			// Update min and max.
			low = Math.min(low, tmp);
			high = Math.max(high, tmp);
		}
		
		// This is what we want to return.
		return high-low <= d ? 1 : 0;
	}
}