#include using namespace std; using T = array,3>,3>; void input(T &A){ for(auto &&vec2 : A) for(auto &&vec1 : vec2) for(auto &&v : vec1) cin >> v; } 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--){ T A, B; input(A), input(B); vector x(3), y, z; iota(x.begin(), x.end(), 0); y = z = x; int ans = 1 << 30; auto check = [&](){ T C{{}}; 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{ do{ 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'; } }