// author : ayush_nishad
#include <bits/stdc++.h>
using namespace std;

#define int int64_t
#define pb push_back
#define in insert
#define F first
#define S second
#define mod 1000000007
#define endl '\n'
#define all(x)  begin(x),end(x)
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define memset(a,b) memset(a,b,sizeof(a))
#define _ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
#define debug(x) cout << "[ " << #x  << " : " << x << " ]" << endl;
#else
#define debug(x)
#endif

void mysol()
{
	int n, m; cin >> n >> m;
	int A[n][m];
	for (auto &a : A)
		for (auto &i : a)
			cin >> i;
	int ans[n][m];
	memset(ans, -1);
	vector<array<int, 2>>v;
	FOR(i, 0, n)
	FOR(j, 0, m)
	v.pb({A[i][j], i});
	sort(all(v));
	auto small = v, large = v;
	reverse(all(large));
	FOR(i, 0, m)
	{
		auto now = small[i];
		ans[now[1]][i] = now[0];
		for (auto &a : large)
		{
			if (a[1] != now[1] and a[0] >= now[0] and ans[a[1]][i] == -1)
			{
				ans[a[1]][i] = a[0];
				a[0] = -1;
			}
		}
	}
	FOR(i, 0, n) {
		FOR(j, 0, m)
		cout << ans[i][j] << ' ';
		cout << endl;
	}
}

int32_t main() {
	_
	int T; cin >> T; while (T--)
		mysol();
	//cerr << sizeof(dp)*(1e-6) << " megabytes\n";
	return 0;
}