#include <iostream>
#include <algorithm>
#include <deque>
#include <math.h>
#include <utility>
#include <vector>

#ifndef ONLINE_JUDGE
    #include "mymodule.h"
#else 
    #define cerr if(false)cerr
#endif

#define ll long long
#define floop(i,n) for(ll i=0;i<n;i++)
#define mod 1000000007
#define mp make_pair


using namespace std;

bool lengthcomp(pair<int, int > a, pair<int, int > b)
{
    return a.first > b.first;
}

bool nstepcomp(pair<int, int > a, pair<int, int > b)
{
    return a.second > b.second;
}

void solve()
{
    ll n, m;
    cin>>n>>m;
    vector< pair<int, int > > v;
    floop(i,n)
    {
        floop(j,m)
        {
            int t;
            cin>>t;
            v.push_back(mp(t, i));
        }
    }
    // floop(i,v.size())
    //     cerr<<v[i].first<<" "<<v[i].second<<endl;
    sort(v.begin(), v.end(), lengthcomp);
    floop(i,v.size())
        cerr<<v[i].first<<" "<<v[i].second<<endl;
    int W[n][m];
    floop(i,n)
        floop(j,m)
            W[i][j] = 0;
    for(int i=0;i<m;i++)
    {
        W[v.back().second][i] = v.back().first;
        v.pop_back();
    }
    cerr<<"64875263"<<endl;
    floop(i,v.size())
        cerr<<v[i].first<<" "<<v[i].second<<endl;
    floop(i,n)
    {
        floop(j,m)
        {
            cerr<<W[i][j]<<" ";
        }
        cerr<<endl;
    }
    sort(v.begin(), v.end(), nstepcomp);
    floop(i,n)
    {
        floop(j,m)
        {
            if(W[i][j]==0)
            {
                W[i][j] = v.back().first;
                v.pop_back();
            }
        }
    }
    cerr<<"fyudqyud"<<endl;
    floop(i,n)
    {
        floop(j,m)
        {
            cout<<W[i][j]<<" ";
        }
        cout<<endl;
    }
    //cout<<"qwerdxsaz"<<endl;
    return;
    //cout<<"vitojri"<<endl;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    #ifndef ONLINE_JUDGE
    freopen("output.txt","w",stdout);
    freopen("input.txt","r",stdin);
    freopen("debug.txt","w",stderr);
    #endif
    
    ll test;
    cin>>test;
    while(test--)
    {
        solve();
        //cout<<"hello"<<endl;
    }

    return 0;
}