
#include<bits/stdc++.h>
#include<algorithm>
#define int long long
#define ll long long
#define endl "\n"
#define ff first
#define ss second
#define pb push_back
#define ios ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define bs binary_search
#define mp make_pair
#define pf push_front
#define pof pop_front()
#define pob pop_back()
#define lb lower_bound
#define up upper_bound
#define ld long double
#define meme(a,no)  memset(a,no,sizeof(a))
#define all(v)  v.begin(),v.end()
 

using namespace std; 

const int INF=1e9+7;

const int N=200000+5;

const int mod=998244353;

int32_t main(){
  ios;
  int T;
  cin>>T;
  //T=1;
  while(T--){
    int n,m;
    cin>>n>>m;
    set<pair<int,pair<int,int>>>global;
    set<pair<int,pair<int,int>>>local[n];
    int i,j,k,l;
    int ans[n][m];
    meme(ans,0);
    for(i=0;i<n;i++){
      for(j=0;j<m;j++){
        int ele;
        cin>>ele;
        local[i].insert({ele,{i,j}});
        global.insert({ele,{i,j}});
      }
    }
    for(i=0;i<m;i++){
      pair<int,pair<int,int>>p1=*global.begin();
      int x=(p1.ss).ff;
      int y=(p1.ss).ss;
      int ele=p1.ff;
      auto it=local[x].find({ele,{x,y}});
      local[x].erase(it);
      global.erase(global.find({ele,{x,y}}));
      ans[x][i]=ele;
    }
    for(i=0;i<n;i++){
      for(j=0;j<m;j++){
        if(ans[i][j]!=0){
          cout<<ans[i][j]<<" ";
          continue;
        }
        pair<int,pair<int,int>>p1=*local[i].begin();
        ans[i][j]=p1.ff;
        cout<<p1.ff<<" ";
        local[i].erase(local[i].find(p1));
      }
      cout<<endl;
    }
    
    
  }    
}