#include #define rep(i,n) for(int i=0; i void chmin(A& l, const A& r){ if(r < l) l = r; } using namespace std; void testcase(){ int P[6][3] = {0,1,2,0,2,1,1,0,2,1,2,0,2,0,1,2,1,0}; int Q[6] = {0,1,1,2,2,1}; int A[3][3][3]; rep(i,3) rep(j,3) rep(k,3) cin >> A[i][j][k]; int X[3][3], Y[3][3], Z[3][3]; rep(i,3) rep(j,3) cin >> X[i][j]; rep(i,3) rep(j,3) cin >> Y[i][j]; rep(i,3) rep(j,3) cin >> Z[i][j]; int x[3][3] = {}, y[3][3] = {}, z[3][3] = {}; rep(i,3) rep(j,3) rep(k,3) x[j][k] += A[i][j][k]; rep(i,3) rep(j,3) rep(k,3) y[i][k] += A[i][j][k]; rep(i,3) rep(j,3) rep(k,3) z[i][j] += A[i][j][k]; int ans = 100; rep(a,6) rep(b,6) rep(c,6){ bool ok = true; rep(j,3) rep(k,3) if(X[j][k] != x[P[b][j]][P[c][k]]) ok = false; rep(i,3) rep(k,3) if(Y[i][k] != y[P[a][i]][P[c][k]]) ok = false; rep(i,3) rep(j,3) if(Z[i][j] != z[P[a][i]][P[b][j]]) ok = false; if(ok) chmin(ans, Q[a] + Q[b] + Q[c]); } if(ans == 100) ans = -1; cout << ans << '\n'; } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; rep(t,T) testcase(); return 0; }