#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
#define fo(i, n) for(int i = 1; i <= n; ++i)
#define pb push_back

int n, m, a[101][101];
int ans[101][101];
vector<pair<int, pair<int, int>>> g;

inline void solve() {
    cin >> n >> m;
    fo(i, n) fo(j, m) {
            cin >> a[i][j];
        }
    vector<pair<int, int> > tire;
    fo(i, m)tire.pb({1e9 + 1, i});
    for (int i = 1; i <= n; ++i) {
        sort(a[i] + 1, a[i] + m + 1);
        for (int j = 0; j < m; ++j) {
            tire[j].first = min(tire[j].first, a[i][j + 1]);
            ans[i][tire[j].second] = a[i][j+1];
        }
        sort(tire.begin(), tire.end());
        reverse(tire.begin(), tire.end());
    }
    fo(i, n) {
        fo(j, m) cout << ans[i][j] << ' ';
        cout << '\n';
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int t;
    cin >> t;
    while (t--) {
        solve();
    }
    return 0;
}
