# include <bits/stdc++.h>
using namespace std;
int n,t,m,x,a[101][101],b[101][101];
int main()
{
    cin>>t;
    while (t--)
    {
        cin>>n>>m;
        for (int i=1;i<=n;i++)
        for (int j=1;j<=m;j++) cin>>a[i][j];
        x=1;
        for (int j=m;j>=1;j--)
        {
            for (int i=1;i<=n;i++) sort(a[i]+1,a[i]+m+1);
            for (int i=1;i<=n;i++)
            if (a[i][1]<a[x][1]) x=i;
            b[x][j]=a[x][1];
            a[x][1]=1e9;
            for (int i=1;i<=n;i++)
            if (i!=x) {b[i][j]=a[i][j];a[i][j]=1e9;}
        }
        for (int i=1;i<=n;i++)
        {
            for (int j=1;j<=m;j++) cout<<b[i][j]<<' ';
            cout<<'\n';
        }
    }
}
