#include <bits/stdc++.h>
using namespace std;

void fast_io() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
}

void solve() {
	int a[3][3][3];
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			for (int k = 0; k < 3; k++) {
				cin >> a[i][j][k];
			}
		}
	}
	int x[3][3];
	int y[3][3];
	int z[3][3];
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			cin >> x[i][j];
		}
	}
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			cin >> y[i][j];
		}
	}
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			cin >> z[i][j];
		}
	}
	int ans = 1e9;
	int iperm[3];
	int jperm[3];
	int kperm[3];
	iota(iperm, iperm + 3, 0);
	iota(jperm, jperm + 3, 0);
	iota(kperm, kperm + 3, 0);
	do {
		int i_diff_cnt = 0;
		for (int i = 0; i < 3; i++) {
			if (iperm[i] != i) {
				i_diff_cnt++;
			}
		}
		int i_op = (i_diff_cnt + 1) / 2;
		do {
			int j_diff_cnt = 0;
			for (int j = 0; j < 3; j++) {
				if (jperm[j] != j) {
					j_diff_cnt++;
				}
			}
			int j_op = (j_diff_cnt + 1) / 2;
			do {
				int k_diff_cnt = 0;
				for (int k = 0; k < 3; k++) {
					if (kperm[k] != k) {
						k_diff_cnt++;
					}
				}
				int k_op = (k_diff_cnt + 1) / 2;
				bool ok = true;
				// x
				for (int j = 0; j < 3; j++) {
					for (int k = 0; k < 3; k++) {
						int su = 0;
						for (int i = 0; i < 3; i++) {
							su += a[i][jperm[j]][kperm[k]];
						}
						if (su != x[j][k]) {
							ok = false;
							break;
						}
					}
				}
				// y
				for (int i = 0; i < 3; i++) {
					for (int k = 0; k < 3; k++) {
						int su = 0;
						for (int j = 0; j < 3; j++) {
							su += a[iperm[i]][j][kperm[k]];
						}
						if (su != y[i][k]) {
							ok = false;
							break;
						}
					}
				}
				// z
				for (int i = 0; i < 3; i++) {
					for (int j = 0; j < 3; j++) {
						int su = 0;
						for (int k = 0; k < 3; k++) {
							su += a[iperm[i]][jperm[j]][k];
						}
						if (su != z[i][j]) {
							ok = false;
							break;
						}
					}
				}
				if (ok) {
					ans = min(ans, i_op + j_op + k_op);
				}

			} while (next_permutation(kperm, kperm + 3));
		} while (next_permutation(jperm, jperm + 3));
	} while (next_permutation(iperm, iperm + 3));
	if (ans == 1e9) {
		cout << "-1\n";
		return;
	}
	cout << ans << "\n";
}
int main() {
	fast_io();
	int t;
	cin >> t;
	for (; t--;) {
		solve();
	}
}