#include<bits/stdc++.h>
using namespace std;

#define ll               long long
#define ull              unsigned long long
#define pll              pair <long long,long long>
#define IM               INT_MAX
#define Im               INT_MIN
#define fast             ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define read             freopen("input.txt", "r", stdin)
#define write            freopen("output.txt", "w", stdout)
#define pb               push_back
#define all(v)           sort(v.begin(),v.end())
#define rall(v)          sort(v.rbegin(),v.rend())
#define rev(v)           reverse(v.begin(),v.end())
#define ff               first
#define ss               second
//#define mod              1000000007
#define lcm(a, b)        ((a)*((b)/__gcd(a,b)))
#define INF              1e18
#define mem(a, b)        memset(a, b, sizeof(a))
#define POPCOUNT         __builtin_popcount

const int mx=1000000007;



void solve()
{

    int n,m;

    cin>>n>>m;

    int a[n+5][m+5];

    bool b[n+5][m+5];

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
            b[i][j]=0;
    }

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
            cin>>a[i][j];
    }

    int k=0;
    while(k<m)
    {

        int mxx,my,mv=IM;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(b[i][j])
                    continue;
                if(a[i][j]<mv)
                {
                    mv=a[i][j];
                    mxx=i,my=j;
                }
            }
        }
        swap(a[mxx][my], a[mxx][k]);
        b[mxx][k]=1;
        k++;
    }

    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
            cout<<a[i][j]<<" ";
        cout<<endl;
    }

}


int main()
{

    fast;

    int t;

    cin>>t;

    while(t--)
        solve();

    return 0;
}
