#include using namespace std; void solve() { int N; cin >> N; vector R(N), C(N), RR(N); set SC; for(int i = 0; i < N; i++) { cin >> R[i]; R[i]--; RR[R[i]] = i; } bool same = true; for(int i = 0; i < N; i++) { cin >> C[i]; C[i]--; SC.insert(C[i]); if(0 < i && C[i - 1] != C[i]) { same = false; } } if(N == 2) { cout << "-1\n"; return; } if(N <= 4 && same) { cout << "-1\n"; return; } int free = 0; while(SC.contains(free) && free < N) { free++; } // cerr << free << "\n"; map nxt; for(int i = 0; i < N; i++) { if(!SC.contains(i)) continue; auto it = SC.upper_bound(i); if(it == SC.end()) { it = SC.begin(); } nxt[i] = *it; } vector> ans(N, vector(N, 0)); for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { ans[i][j] = R[i]; } } vector used(N, false); int last_free = 0; for(int j = 0; j < N; j++) { if(!used[C[j]] && !same) { used[C[j]] = true; ans[RR[nxt[C[j]]]][j] = C[j]; } else if(free < N) { ans[RR[free]][j] = C[j]; last_free = free; free++; while(SC.contains(free) && free < N) { free++; } } else { ans[RR[last_free]][j] = C[j]; } } for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { cout << ans[i][j] + 1 << " "; } cout << "\n"; } // for(int i = 0; i < N; i++) { // for(int j = 0; j < N; j++) { // if(!used[C[j]]) { // used[C[j]] = true; // } // else { // cout << R[i] + 1 << " "; // } // } // cout << "\n"; // } return; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int T; cin >> T; while(T--) { solve(); } return 0; }