#!/usr/bin/ python3.8 import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines T = int(readline()) def test(A): if any(x <= 0 for x in A): return False def is_kadomatsu(a, b, c): if a == c: return False return (a < b > c) or (a > b < c) return all(is_kadomatsu(A[i], A[j], A[k]) for i, j, k in ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))) def solve(): L = int(readline()) A = [0] * 9 for i in range(3): A[3 * i: 3 * i + 3] = map(int, readline().split()) i, j = (i for i, x in enumerate(A) if not x) nums = [L, L + 1] for x in A: nums.append(x - 1) nums.append(x) nums.append(x + 1) nums.append(L - x + 1) nums.append(L - x) nums.append(L - x - 1) for k in range(3): nums.append(L // 2 - k) nums.append(L // 2 + k) nums = sorted(set(x for x in nums if 1 <= x <= L)) ret = 0 for n, m in zip(nums, nums[1:]): A[i] = n A[j] = L - n if test(A): ret += m - n return ret for _ in range(T): print(solve())