#include<bits/stdc++.h>
#define ll long long

using namespace std;

int main(){
	ll t;
	cin>>t;
	while(t--){
		multiset<pair<int,int>>s;
	    ll n,m;
		cin>>n>>m;
		ll arr[n][m];
		for(ll i=0;i<n;i++){
			for(ll j=0;j<m;j++){
				ll x;
				cin>>x;
				arr[i][j]=-1;
				s.insert({x,i});
			}
		}
		ll k=0;
		for(ll i=0;i<m;i++){
			auto it=s.begin();
			arr[it->second][i]=it->first;
			s.erase(it);
		}
		while(!s.empty()){
			
			auto it=s.begin();
			ll y=0;
			while(arr[it->second][y]!=-1)
			    y++;
			arr[it->second][y]=it->first;
			s.erase(it);
		}
		for(ll i=0;i<n;i++){
			for(int j=0;j<m;j++)
			   cout<<arr[i][j]<<" ";
			cout<<'\n';
		}
	}
	
	return 0;
}