#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define INF 2000011
typedef long long ll;
typedef struct node node;
typedef pair<int, int> pii;
typedef vector<vector<int>> vvi;
typedef vector<pii> vpii;
typedef unsigned long long int ulli;
#define pb(a) push_back(a)
#define fr(i, n) for(i=0; i<n; i++)
#define mp(a, b) make_pair(a, b)
#define p_q(node) priority_queue<node, vector<node>, compare>
multimap<int, int> mp;
void solve()
{
    mp.clear();
	int n, m;
	cin>>n>>m;
	
	int data;
	multimap<int, int> :: iterator p;
	for(int i=0; i<n; i++)
	{
		for(int j=0; j<m; j++)
		{
			cin>>data;
			mp.insert(mp(data, i));
		}
	}
	int vis[n][m];
	memset(vis, -1, sizeof(vis));
	for(int j=0; j<m; j++)
	{
	    p=mp.begin();
	    vis[p->second][j]=p->first;
	    mp.erase(p);
	}
	while(!mp.empty())
	{
	     p=mp.begin();
	    for(int j=0; j<m; j++)
	    {
	        if(vis[p->second][j]==-1)
	        {
	            vis[p->second][j]=p->first;
	            break;
	        }
	    }
	    mp.erase(p);
	}
	for(int i=0; i<n; i++)
	{
		for(int j=0; j<m;j++)
		{
			cout<<vis[i][j]<<" ";
		}
		cout<<endl;
	}
}
int main()
{

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