#include <bits/stdc++.h>
#define tez ios_base::sync_with_stdio(false);cin.tie(NULL);
#define ll long long
#define ull unsigned long long
#define pb push_back
#define mb make_pair
#define el "\n"
#define MAX 100005
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	tez
	ll t;
	cin >> t;
	while (t--)
	{
		ll n, m;
		cin >> n >> m;
		vector <vector <int>> path(n, vector <int>(m));
		vector <vector <int>> ans(n, vector <int>(m));
		for (ll i = 0; i < n; ++i)
		{
			for (ll j = 0; j < m; ++j)
				cin >> path[i][j];
			sort(path[i].begin(), path[i].end());
		}
		for (ll i = 0; i < m; ++i)
		{
			if (i != (m - 1))
			{	ll st = *path[0].begin();
				path[0].erase(path[0].begin());
				ans[0][i] = st;
				ll ind = 0;
				for (ll j = 1; j < n; ++j)
				{
					// cout << "YES";
					if (path[j][0] < st)
					{
						path[ind].insert(path[ind].begin(), st);
						st = path[j][0];
						ans[ind][i] = *path[ind].rbegin();
						path[ind].pop_back();
						ind = j;
						ans[j][i] = st;
						path[j].erase(path[j].begin());
					}
					else
					{
						ans[j][i] = *path[j].rbegin();
						path[j].pop_back();
					}
				}
			}
			else
			{
				for (ll j = 0; j < n; ++j)
					ans[j][i] = *path[j].begin();
			}
		}
		// cout << "YES";
		for (ll i = 0; i < n; ++i)
		{
			for (ll j = 0; j < m; ++j)
				cout << ans[i][j] << " ";
			cout << el;
		}
	}
	return 0;
}