#include <iostream>
#include <algorithm>
using namespace std;
const int N = 105;
void *memset(void *str, int c, size_t n);
int arr[N][N];
struct point{
int p_x,p_y;
int value;
}p[N*N];
bool com(point j,point k);
int main(){
int i,m,n,a=0;
memset(arr,0,sizeof arr);
cin>>i;
for(;i>0;i--){
cin>>n>>m;
for(int x=1;x<=n;x++)
for(int q=1;q<=m;q++){
p[++a].p_x = x;
p[a].p_y = q;
cin>>p[a].value;}
sort(p+1,p+1+a,com);
for(int q=1;q<=m;q++)
arr[p[q].p_x][q] = p[q].value;
for(int x=m+1;x<=a;x++)
for(int q=1;q<=m;q++){
if( arr[p[x].p_x][q] == 0){
arr[p[x].p_x][q]=p[x].value;
break;
}}
for(int x=1;x<=n;x++){
for(int q=1;q<=m;q++){
cout<<arr[x][q]<<' ';}
cout<<endl;}
}
return 0;
}
bool com(point j,point k){
return j.value<k.value;}