# Arup Guha
# 2/19/2025
# Solution to COP 4516 Final Individual Contest Problem A: Almost Magic Square

# Returns 1 if the values in nums permuted according to perm form a d
# Almost Magic Square, and returns 0 otherwise.
def eval(nums, perm, d):

    # There are eight groups to consider, here I store the indexes of each.
    # These are really indexes into perm.
    GROUPS = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]

    # This is the sum of the first row.
    firstsum = 0
    for i in range(3):
        firstsum += nums[perm[GROUPS[0][i]]]

    # These will get overwritten.
    mymin = 1000000000
    mymax = 0

    # Try each group.
    for i in range(len(GROUPS)):

        # Add the number in this row, col or diag.
        mys = 0
        for j in range(len(GROUPS[i])):
            mys += nums[perm[GROUPS[i][j]]]

        # Update.
        mymin = min(mymin, mys)
        mymax = max(mymax, mys)

    # Return accordingly.
    if mymax - mymin <= d:
        return 1
    return 0

# Solves the problem where the first k items of perm are fixed.
def go(nums, perm, used, d, k):

    # Done filling it in so evaluate...
    if k == len(perm):
        return eval(nums, perm, d)

    # Set up accumulator variable.
    res = 0
    
    # Try each unused number in slot k.
    for i in range(len(perm)):

        # We've used this one before.
        if used[i]:
            continue

        # Try this and add in results.
        used[i] = True
        perm[k] = i
        res += go(nums, perm, used, d, k+1)
        used[i] = False

    # Ta da!
    return res

def main():

    nC = int(input())

    # Process cases.
    for loop in range(nC):

        # Get input.
        d = int(input())
        vals = [int(x) for x in input().split()]

        # Initialize these.
        used = []
        perm = []
        for i in range(9):
            used.append(False)
            perm.append(0)

        # Ta da!
        print(go(vals, perm, used, d, 0))

# Run it!
main()
