#include <bits/stdc++.h> 

using namespace std; 

const int MOD = 1000000007;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector<int> vi;

#define FOR(i, b, c) for (int(i) = (b); (i) < (c); (i)++)
#define FORD(i, b, c) for (int(i) = (b); (i) >= (c); i--)

#define reset(a, b) memset(a, b, sizeof(a))
#define SYNC ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ALL(a) a.begin(), a.end()
#define RALL(a) a.rbegin(), a.rend()
#define pb push_back
#define mp make_pair

ll power(ll a,ll b, ll m)
{
    a%=m;
    if(b==1)
    return a;
    if(b==0)
    return 1LL;
    ll ret=power(a,b/2,m);
    ret=(ret*ret)%m;
    if(b&1)
    ret=(ret*a)%m;
    return ret;
}

void solve(){
    int n,m,tmp;
    cin>>n>>m;
    vi a[n];
    FOR(i,0,n){
        FOR(j,0,m){
            cin>>tmp;
            a[i].pb(tmp);
        }
    }
    FOR(i,0,n){
        sort(ALL(a[i]));
    }
    int i = 0;
    int num=0;
    int ans[n][m];
    FORD(i,m,1){
        int mx = INT_MAX, d=-1;
        FOR(j,0,n){
            if(a[j][0] < mx){
                mx=a[j][0];
                d=j;
            }            
        }
        rotate(a[d].begin(), a[d].begin()+1, a[d].begin()+i);
    }
    FOR(i,0,n){
        FOR(j,0,m){
            cout << a[i][j] << " ";
        }
        cout<<"\n";
    }

}

int main()
{
    SYNC;
    int t;
    cin >> t;
    while(t--){
        solve();
    }
    return 0;
}