#include<bits/stdc++.h>
#define add insert
#define endl "\n"
#define pb push_back

using ll = long long;
using namespace std;

ll arr[103][103];
ll used[103][103];
ll ans[103][103];
void solve(){
    ll m, n;
    vector<ll> v;
    cin >> n >> m;
    for(ll i = 0; i < n; ++i){
        for(ll j = 0; j < m; ++j){
            cin >> arr[i][j];
            v.pb(arr[i][j]);
            used[i][j] = 0;
        }
    }
    sort(v.begin(), v.end());
    for(ll i = 0; i < m; ++i){
        for(ll j = 0; j < n; ++j){
            for(ll k = 0; k < m; ++k){
                if(arr[j][k] == v[i] && used[j][k] == 0){
                    used[j][k] = i+1;
                    goto san;
                }
            }
        }
        san:;
    }

    for(ll i = 0; i < m; ++i){
         for(ll j = 0; j < n; ++j){
            bool f = false;
            ll fk = -1;
            for(ll k = 0; k < m; ++k){
                if(used[j][k] == i+1){
                    f = true;
                    fk = k;
                    break;
                }
            }

            if(f){
                ans[i][j] = arr[j][fk];
            } else {
                for(ll k = 0; k < m; ++k){
                    if(used[j][k] == 0){
                        used[j][k] = i+1;
                        fk = k;
                        break;
                    }
                }
                ans[i][j] = arr[j][fk];
            }
         }
    }

    for(ll i = 0; i < n; ++i){
        for(ll j = 0; j < m; ++j){
            cout << ans[j][i] << ' ';
        }
        cout << endl;
    }

    
}


int main(){
    ll t;
    cin >> t;
    while(t--){
        solve();
    }
}