#include using namespace std; template istream& operator >> (istream& is, vector& vec) { for(T& x : vec) is >> x; return is; } int main(){ ios::sync_with_stdio(false); cin.tie(0); int T; cin >> T; vector dp(3 * 3 * 3, 2); dp[0 + 1 * 3 + 2 * 9] = 0; dp[1 + 0 * 3 + 2 * 9] = dp[2 + 1 * 3 + 0 * 9] = dp[0 + 2 * 3 + 1 * 9] = 1; while(T--){ vector A(3, vector(3, vector(3))), B(3, vector(3, vector(3))); cin >> A >> B; vector x(3), y, z; iota(x.begin(), x.end(), 0); y = z = x; int ans = 1 << 30; auto check = [&](){ vector C(3, vector(3, vector(3))); for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ for(int k = 0; k < 3; k++){ C[0][y[j]][z[k]] += A[i][j][k]; C[1][x[i]][z[k]] += A[i][j][k]; C[2][x[i]][y[j]] += A[i][j][k]; } } } return C == B; }; auto f = [&](vector &x){return x[0] + x[1] * 3 + x[2] * 9;}; do{ sort(y.begin(), y.end()); do{ sort(z.begin(), z.end()); do{ if(check()) ans = min(ans, dp[f(x)] + dp[f(y)] + dp[f(z)]); }while(next_permutation(z.begin(), z.end())); }while(next_permutation(y.begin(), y.end())); }while(next_permutation(x.begin(), x.end())); if(ans >> 30) ans = -1; cout << ans << '\n'; } }