#include <bits/stdc++.h>
using namespace std;
using namespace __detail;

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define ar array
#define vi vector<int>
#define vvi vector<vector<int>>
#define vll vector<long long>
#define all(x) (x).begin(), (x).end()
#define en '\n'
#define FILL(x, v) memset(x, v, sizeof(x))
#define pb push_back
#define fast                   \
  ios::sync_with_stdio(false); \
  cin.tie(NULL);               \
  cout.tie(NULL);
#define F_OR(i, a, b, s) \
  for (int i = (a); ((s) > 0 ? i < (b) : i > (b)); i += (s))
#define F_OR1(e) F_OR(i, 0, e, 1)
#define F_OR2(i, e) F_OR(i, 0, e, 1)
#define F_OR3(i, b, e) F_OR(i, b, e, 1)
#define F_OR4(i, b, e, s) F_OR(i, b, e, s)
#define GET5(a, b, c, d, e, ...) e
#define F_ORC(...) GET5(__VA_ARGS__, F_OR4, F_OR3, F_OR2, F_OR1)
#define FOR(...)     \
  F_ORC(__VA_ARGS__) \
  (__VA_ARGS__)

#define E_ACH2(x, a) for (auto &x : a)
#define E_ACH3(x, y, a) for (auto &[x, y] : a)
#define E_ACH4(x, y, z, a) for (auto &[x, y, z] : a)
#define E_ACHC(...) GET5(__VA_ARGS__, E_ACH4, E_ACH3, E_ACH2)
#define EACH(...)     \
  E_ACHC(__VA_ARGS__) \
  (__VA_ARGS__)

template <typename A, typename B>
inline void chmin(A &a, B b) {
  if (a > b) a = b;
}
template <typename A, typename B>
inline void chmax(A &a, B b) {
  if (a < b) a = b;
}

/*
DEBUG: -D LOCAL
debug() << imie(k) imie(x) imie(row) imie(col);
find m smallest numbers, adjust it to the j'th column
after that, fill the j'th column with maximum numbers without replacing one of
the m smallest numbers
*/

const int N = 105;
ll ans[N][N];

void solve() {
  int n, m;
  cin >> n >> m;
  vector<multiset<int>> A(n);
  multiset<pii> st;

  FOR(n) {
    FOR(j, m) {
      int x;
      cin >> x;
      A[i].insert(x);
      st.insert({x, i});
    }
  }

  int j = 0;
  while (!st.empty()) {
    pii x = *(st.begin());
    st.erase(st.begin());
    ans[x.second][j] = x.first;

    FOR(n) {
      if (i == x.second) {
        continue;
      }
      int y = *(prev(A[i].end()));
      ans[i][j] = y;

      st.erase(st.find({y, i}));
      A[i].erase(A[i].find(y));
    }
    j++;
  }

  FOR(n) {
    FOR(j, m) { cout << ans[i][j] << " "; }
    cout << en;
  }
}

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