#include<iostream>
#include<algorithm>
using namespace std;
int t, n, a[2005][2005], ans[1000005];
int main()
{
cin >> t;
while(t --)
{
cin >> n;
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
cin >> a[i][j];
}
}
int cnt = 0;
for(int i = 1; i <= n; i ++)
{
if(i % 2 == 0)
{
for(int j = n; j >= 0; j --)
{
ans[++ cnt] = a[i][j];
}
}
else
{
for(int j = 1; j <= n; j ++)
{
ans[++ cnt] = a[i][j];
}
}
}
int x = 0, y = 0;
for(int i = 1; i < n * n; i ++)
{
if(ans[i] > ans[i + 1]) x ++;
else y ++;
}
if(x < y)
{
reverse(ans + 1, ans + n * n + 1);
}
for(int i = 1; i < n * n; i ++)
{
cout << ans[i] << " ";
}
cout << ans[n * n] << endl;
}
return 0;
}