#include using namespace std; #ifdef TEMPURA #else #define debug(...) ((void)0) #define msg(...) ((void)0) #endif #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define REP(i, m, n) for(int i = (int)(m); i < (int)(n); i++) using ll = long long; using ull = unsigned long long; using i128 = __int128_t; template inline bool chmin(T &a, T b) { if(a > b) { a = b; return true; } return false; } template inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; } // #include // using mint = atcoder::modint998244353; struct Xor128 { unsigned x, y, z, w; Xor128() : x(123456789), y(362436069), z(521288629), w(88675123){}; inline unsigned xor128() { unsigned t; t = x ^ (x << 11); x = y; y = z; z = w; return w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); } int nextInt(int x, int y) { return x + ((ull(xor128()) * (y - x)) >> 32); } double nextDouble(double a, double b) { return (double)(xor128() & 0xffff) / 0xffff * (b - a) + a; } }; auto rnd = Xor128(); vector> create_random_path(int l, int r, int u, int d, int x, int y) { if(l > r || u > d) { return {}; } if(rnd.nextInt(0, 2)) { auto v = x == l ? create_random_path(l + 1, r, u, d, x + 1, u + d - y) : create_random_path(l, r - 1, u, d, x - 1, u + d - y); if(y == u) { for(int j = d; j >= u; j--) { v.push_back({x, j}); } } else { for(int j = u; j <= d; j++) { v.push_back({x, j}); } } return v; } else { auto v = y == u ? create_random_path(l, r, u + 1, d, l + r - x, y + 1) : create_random_path(l, r, u, d - 1, l + r - x, y - 1); if(x == l) { for(int j = r; j >= l; j--) { v.push_back({j, y}); } } else { for(int j = l; j <= r; j++) { v.push_back({j, y}); } } return v; } } void solve() { int n; cin >> n; vector a(n * n); rep(i, n * n) cin >> a[i]; int s = 0; rep(i, n * n) s += a[i]; if(s % n != 0) { cout << -1 << endl; return; } rep(_, 10) { auto v = create_random_path(0, n - 1, 0, n - 1, 0, 0); vector ord; for(auto [x, y] : v) { ord.push_back(x * n + y); } vector sum(n * n + 1); rep(i, n * n) { sum[i + 1] = (sum[i] + a[ord[i]]) % n; } vector cnt(n); rep(i, n * n) { cnt[sum[i]] += 1; } if(cnt[0] < n) { continue; } vector ans(n * n); int cur = 1; rep(i, n * n) { ans[ord[i]] = cur; if(sum[i + 1] == 0) { cur = min(n, cur + 1); } } rep(i, n * n) { cout << ans[i] << " \n"[i % n == n - 1]; } return; } cout << -1 << endl; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; while(t--) { solve(); } }