#include <bits/stdc++.h>
using namespace std;
#define int long long
void read (int &x) {
    char ch = getchar(); int f = 0; x = 0;
    while (!isdigit(ch)) { if (ch == '-') f = 1; ch = getchar(); }
    while (isdigit(ch)) x = x * 10 + ch - 48, ch = getchar();
    if (f) x = -x;
} const int N = 105;
int n, m, a[N][N], o[N][N], k[N][N];
struct qwq {
    int val, x, y;
    bool operator < (const qwq &p) const {
        return val < p.val;
    }
} b[N * N], v[N][N]; int it[N];
signed main() {
    int T; read (T);
    while (T--) {
        read (n), read (m); int c = 0;
        for (int i = 1; i <= n; ++i) it[i] = 1;
        for (int i = 1; i <= n; ++i)
            for (int j = 1; j <= m; ++j) {
                read (a[i][j]), b[++c] = {a[i][j], i, j};
                v[i][j] = {a[i][j], i, j};
                k[i][j] = 0;
            }
            for (int i = 1; i <= m; ++i)
                for (int j = 1; j <= n; ++j) k[i][j] = 0;
        sort (b + 1, b + c + 1);
        for (int i = 1; i <= n; ++i) sort (v[i] + 1, v[i] + m + 1);
        for (int i = 1; i <= m; ++i) {
            o[b[i].x][i] = b[i].val, ++it[b[i].x], k[i][b[i].x] = 1;
        }
        for (int i = 1; i <= n; ++i) {
            int ii = 1;
            for (int j = it[i]; j <= m; ++j) {
                while (k[ii][i]) ++ii; o[i][ii] = v[i][j].val; ++ii;
            }
        }
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= m; ++j) printf ("%lld ", o[i][j]); puts ("");
        }
    }
}
