#include<bits/stdc++.h>
using namespace std;
typedef  long long ll;

int main(){

  int t;
  cin>>t;

  while (t--)
  {
      vector<tuple<ll, ll, ll> > a;
       ll n,m;
       cin>>n>>m;
       ll mat[101][101]={0};
       for (int i = 0; i < n; i++)
       {
          for (int j = 0; j < m; j++)
          {
             ll tem;
             cin>>tem;
            a.push_back(make_tuple(tem, i, j));

          }

       }
       sort(a.begin(),a.end());

     for (int i = 0; i < m; i++)
     {

        mat[get<1>(a[i])][i]=get<0>(a[i]);


     }
     for (int i = m; i < n*m; i++)
     {
        for (int j = 0; j < m; j++)
        {
           if(mat[get<1>(a[i])][j]==0){
              mat[get<1>(a[i])][j]=get<0>(a[i]);
              break;
           }
        }
     }






       for (int i = 0; i < n; i++)
       {
          for (int j = 0; j < m; j++)
          {
             cout<<mat[i][j]<<" ";
          }
          cout<<endl;

       }









  }

}
