#include using namespace std; using ll = long long; constexpr int inf32 = numeric_limits::max() / 2; constexpr ll inf64 = numeric_limits::max() / 2; template bool chmin(T1 &a, T2 b) { return a > b ? a = b, true : false; } template bool chmax(T1 &a, T2 b) { return a < b ? a = b, true : false; } void solve() { int N; cin >> N; vector R(N), C(N); for (auto &e : R) cin >> e, e--; for (auto &e : C) cin >> e, e--; vector> A(N, vector(N)); auto rec = [&] (auto rec, int r, int c) -> bool { if (r == N) { bool ok = true; for (int i = 0; i < N; i++) { vector cnt(N); for (int j = 0; j < N; j++) cnt[A[i][j]]++; int pos = max_element(cnt.begin(), cnt.end()) - cnt.begin(); if (count(cnt.begin(), cnt.end(), cnt[pos]) >= 2) ok = false; if (pos != R[i]) ok = false; } for (int j = 0; j < N; j++) { vector cnt(N); for (int i = 0; i < N; i++) cnt[A[i][j]]++; int pos = max_element(cnt.begin(), cnt.end()) - cnt.begin(); if (count(cnt.begin(), cnt.end(), cnt[pos]) >= 2) ok = false; if (pos != C[j]) ok = false; } return ok; } for (int a = 0; a < N; a++) { A[r][c] = a; int nr = r, nc = c + 1; if (nc == N) nr = r + 1, nc = 0; if (rec(rec, nr, nc)) return true; } return false; }; if (N <= 3) { if (rec(rec, 0, 0)) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << A[i][j] << " \n"[j + 1 == N]; } } } else { cout << -1 << '\n'; } return; } for (int i = 0; i < N; i++) A[i] = vector(N, R[i]); for (int j = 0; j < N; j++) { for (int i = 0; i < N; i++) { if (A[i][j] == C[j]) { A[(i + 1) % N][j] = C[j]; break; } } } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << A[i][j] + 1 << " \n"[j + 1 == N]; } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) solve(); }