#pragma GCC optimize(3, "Ofast", "inline")

#include <bits/stdc++.h>

#define rep(i,a,b) for(int i=(a);i<=(b);i++)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
typedef pair<double, double> Pd;
typedef pair<ll, ll> pll;
const int maxn = 1e6+10;



int n,m;
int a[111][111];
struct node
{
	int x,y;
	int v;
}e[10005];

int tot = 0;
bool cmp(node A,node B) {
	return A.v<B.v;
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("/volumes/D/acm/1.txt", "r", stdin);
#endif
  
    int T;
    scanf("%d",&T);
    while(T--) {
    	tot = 0;
    	scanf("%d%d",&n,&m);
    	rep(i,1,n) {
    		rep(j,1,m) {
    			scanf("%d",&a[i][j]);
    			e[++tot]={i,j,a[i][j]};
    		}
    	}
    	sort(e+1,e+1+tot,cmp);
    	for(int i=1;i<=m;i++) {
    		int x = e[i].x;
    		int y = e[i].y;
    		int z = e[i].v;
    		for(int j=i+1;j<=m;j++) {
    			if(e[j].v==a[x][i]&&e[j].x==x&&e[j].y==i) {
    				e[j].y=y;
    				break;
    			}
    		}
    		swap(a[x][i],a[x][y]);
    	}
    	rep(i,1,n) {
    		rep(j,1,m) {
    			printf("%d",a[i][j]);
    			if(j!=m) printf(" ");
    			else printf("\n");
    		}
    	}
    }
    return 0;
}