#include <bits/stdc++.h>
#include <chrono>
using namespace std;
using namespace chrono;
// "AJEET JAIN"----"JAI JINENDRA"
/* "णमो अरिहंताणं",
"णमो सिद्धाणं",
"णमो आयरियाणं",
"णमो उवज्झायाणं",
"णमो लोए सव्वसाहूणं",
"",
"एसो पंच नमोक्कारो, सव्व पावप्पणासणो",
"मंगलाणं च सव्वेसिं, पडमं हवै मंगलं", */
// Aliases to op
using ll = long long;
using ull = unsigned long long;
using ld = double;
using vll = vector<ll>;
// Constants
constexpr ll INF = 4e18;
constexpr ld EPS = 1e-9;
constexpr ll MOD = 1e9 + 7;
// Macros
#define F first
#define S second
#define all(x) begin(x), end(x)
#define allr(x) rbegin(x), rend(x)
#define py cout<<"YES\n";
#define pn cout<<"NO\n";
#define forn(i,n) for(int i=0;i<n;i++)
#define for1(i,n) for(int i=1;i<=n;i++)
// #define insert push_back
#define pb push_back
#define MP make_pair
#define endl '\n'
/*
ROUGH --
*/
void AJNJ() {
ll n;
cin >> n;
vector<vll> v(n + 2, vll(n + 2, 0));
vector<vll> mark(n + 2, vll(n + 2, 0));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> v[i][j];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
ll k = v[i][j];
int chk = 0;
if (j + 1 <= n && v[i][j + 1] == k){
chk++;
}
if (j - 1 >= 1 && v[i][j - 1] == k){
chk++;
}
if (i - 1 >= 1 && v[i - 1][j] == k){
chk++;
}
if (i + 1 <= n && v[i + 1][j] == k){
chk++;
}
if (chk >= 2) {
mark[i][j] = 1;
}
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (!mark[i][j]) continue;
ll k = v[i][j];
if (j + 1 <= n && v[i][j + 1] == k){
mark[i][j + 1] = 1;
}
if (j - 1 >= 1 && v[i][j - 1] == k){
mark[i][j - 1] = 1;
}
if (i - 1 >= 1 && v[i - 1][j] == k){
mark[i - 1][j] = 1;
}
if (i + 1 <= n && v[i + 1][j] == k){
mark[i + 1][j] = 1;
}
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (mark[i][j]) v[i][j] = 0;
}
}
for (int j = 1; j <= n; j++) {
vll col;
for (int i = n; i >= 1; i--) {
if (v[i][j] > 0) col.push_back(v[i][j]);
}
int idx = 0;
for (int i = n; i >= 1; i--) {
if (idx < (ll)col.size()){
v[i][j] = col[idx++];
}
else {
v[i][j] = 0;
}
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << v[i][j] << " ";
}
cout << endl;
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T = 1;
cin>>T;
auto start1 = high_resolution_clock::now();
while(T--){
AJNJ();
}
auto stop1 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop1 - start1);
cerr << "Time: " << duration . count() / 1000 << " ms" << endl;
return 0;
}