The 2050 volunteers are organizing the "Run! Chase the Rising Sun" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town.

There are $n+1$ checkpoints on the trail. They are numbered by $0$, $1$, ..., $n$. A runner must start at checkpoint $0$ and finish at checkpoint $n$. No checkpoint is skippable — he must run from checkpoint $0$ to checkpoint $1$, then from checkpoint $1$ to checkpoint $2$ and so on. Look at the picture in notes section for clarification.

Between any two adjacent checkpoints, there are $m$ different paths to choose. For any $1\le i\le n$, to run from checkpoint $i-1$ to checkpoint $i$, a runner can choose exactly one from the $m$ possible paths. The length of the $j$-th path between checkpoint $i-1$ and $i$ is $b_{i,j}$ for any $1\le j\le m$ and $1\le i\le n$.

To test the trail, we have $m$ runners. Each runner must run from the checkpoint $0$ to the checkpoint $n$ once, visiting all the checkpoints. Every path between every pair of adjacent checkpoints needs to be ran by exactly one runner. If a runner chooses the path of length $l_i$ between checkpoint $i-1$ and $i$ ($1\le i\le n$), his tiredness is $$\min_{i=1}^n l_i,$$ i. e. the minimum length of the paths he takes.

Please arrange the paths of the $m$ runners to minimize the sum of tiredness of them.


-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10000$). Description of the test cases follows.

The first line of each test case contains two integers $n$ and $m$ ($1 \leq n,m \leq 100$).

The $i$-th of the next $n$ lines contains $m$ integers $b_{i,1}$, $b_{i,2}$, ..., $b_{i,m}$ ($1 \le b_{i,j} \le 10^9$).

It is guaranteed that the sum of $n\cdot m$ over all test cases does not exceed $10^4$.


-----Output-----

For each test case, output $n$ lines. The $j$-th number in the $i$-th line should contain the length of the path that runner $j$ chooses to run from checkpoint $i-1$ to checkpoint $i$. There should be exactly $m$ integers in the $i$-th line and these integers should form a permuatation of $b_{i, 1}$, ..., $b_{i, m}$ for all $1\le i\le n$.

If there are multiple answers, print any.


-----Examples-----

Input
2
2 3
2 3 4
1 3 5
3 2
2 3
4 1
3 5
Output
2 3 4
5 3 1
2 3
4 1
3 5


-----Note-----

In the first case, the sum of tiredness is $\min(2,5) + \min(3,3) + \min(4,1) = 6$.

In the second case, the sum of tiredness is $\min(2,4,3) + \min(3,1,5) = 3$.

Source: codeforces | Difficulty: EASY
Tags: Greedy algorithms

Sorting

Constructive algorithms


Solutions:
import sys
input = sys.stdin.readline

def solve():
	(n, m) = map(int, input().split())
	a = [None] * (n * m)
	b = [None] * n
	w = [None] * n
	for i in range(n):
		j = 0
		c = [None] * m
		w[i] = [None] * m
		for v in map(int, input().split()):
			a[i * m + j] = (v, i, j)
			c[j] = v
			j += 1
		b[i] = c
	a.sort()
	k = 0
	for (v, i, j) in a[:m]:
		w[i][k] = j
		k += 1
	for i in range(n):
		h = [False] * m
		for j in w[i]:
			if j is not None:
				h[j] = True
		k = 0
		for j in range(m):
			if w[i][j] is None:
				while k < m and h[k]:
					k += 1
				w[i][j] = k
				k += 1
		print(' '.join((str(b[i][j]) for j in w[i])))
for i in range(int(input())):
	solve()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().rstrip().split())
	li = []
	for i in range(n):
		for v in map(int, input().rstrip().split()):
			li.append((v, i))
	li.sort()
	selected = li[:m]
	not_selected = li[m:]
	new_not_selected = [[] for _ in range(n)]
	for (v, i) in not_selected:
		new_not_selected[i].append(v)
	result = []
	for s in selected:
		(selected_value, selected_route_part) = s
		temp = []
		for j in range(n):
			if j == selected_route_part:
				temp.append(selected_value)
			else:
				temp.append(new_not_selected[j].pop())
		result.append(temp)
	new_result = list(zip(*result))
	for v in new_result:
		print(' '.join(map(str, v)))


t = int(input())

def compare(a):
	return a[0]
for _ in range(t):
	(n, m) = [int(i) for i in input().split()]
	paths = []
	t = 1
	for i in range(n):
		paths.append([[int(i), t, id] for (id, i) in enumerate(input().split())])
		t += 1
	topath = []
	for i in range(len(paths)):
		topath.extend(paths[i])
	topath.sort(key=compare)
	bestpath = topath[:m]
	res = []
	for i in range(len(paths)):
		new_path = [0] * m
		path_set = set()
		for j in range(len(bestpath)):
			if bestpath[j][1] == i + 1:
				new_path[j] = bestpath[j][0]
				path_set.add(bestpath[j][2])
		p = 0
		l = 0
		while p < m and l < m:
			while l in path_set:
				l += 1
			while p < m and new_path[p] != 0:
				p += 1
			if p < m and l < m:
				new_path[p] = paths[i][l][0]
				p += 1
				l += 1
		res.append(new_path)
	for i in res:
		print(' '.join(map(str, i)))


t = int(input())
for i in range(t):
	(n, m) = map(int, input().strip().split(' '))
	l = []
	l1 = []
	for j in range(n):
		lst = list(map(int, input().strip().split(' ')))
		l.append(lst)
		l1 = l1 + lst
	l1.sort()
	m1 = 0
	t1 = 0
	for j in range(n):
		l[j].sort()
		if m1 == m or l[j][0] > l1[m - 1]:
			for j1 in range(m):
				print(l[j][j1], end=' ')
			print()
		else:
			t1 = m1
			k1 = []
			for j1 in range(m):
				if m1 < m and l[j][j1] <= l1[m - 1 - m1]:
					ind = l1.index(l[j][j1])
					del l1[ind]
					m1 += 1
				else:
					k1.append(l[j][j1])
			for j1 in range(t1):
				print(k1[j1], end=' ')
			for j1 in range(t1, m1):
				print(l[j][j1 - t1], end=' ')
			for j1 in range(m1, m):
				print(l[j][j1], end=' ')
			print()


for case in range(int(input())):
	(n, m) = (int(i) for i in input().split())
	p = [sorted([int(i) for i in input().split()]) for j in range(n)]
	pp = [[] for i in p]
	for iii in range(m):
		mn = min(range(n), key=lambda x: p[x][0])
		for i in range(len(p)):
			pp[i].append(p[i].pop(0) if i == mn else p[i].pop())
	for t in pp:
		print(*t)


from sys import stdin, stdout
import math

def ii():
	return int(stdin.readline())

def mi():
	return map(int, stdin.readline().split())

def li():
	return list(mi())

def si():
	return stdin.readline()
for _ in range(ii()):
	A = []
	(n, m) = mi()
	for i in range(n):
		l1 = li()
		for j in range(m):
			A.append([l1[j], i, j])
	A.sort()
	ans = [[-1 for j in range(m)] for i in range(n)]
	for i in range(m * n):
		(v, a, b) = A[i]
		if i < m:
			ans[a][i] = v
		else:
			for j in range(m):
				if ans[a][j] == -1:
					ans[a][j] = v
					break
	for i in ans:
		print(*i)


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = []
	b = []
	for i in range(n):
		a.append(list(map(int, input().split())))
		for j in range(m):
			b.append([a[i][j], i])
	b.sort()
	c = [[0 for i in range(m)] for i in range(n)]
	for i in range(m):
		c[b[i][1]][i] = b[i][0]
	for y in range(m, n * m):
		j = 0
		while c[b[y][1]][j] != 0:
			j += 1
		c[b[y][1]][j] = b[y][0]
	for i in c:
		for j in i:
			print(j, end=' ')
		print()


def main():
	cases = int(input())
	from collections import deque
	for case in range(cases):
		(n, m) = map(int, input().split())
		stacks = [sorted(map(int, input().split())) for i in range(n)]
		paths = []
		for i in range(m):
			minis = [stacks[i][0] for i in range(n)]
			i_mini = minis.index(min(minis))
			path = [0] * n
			path[i_mini] = stacks[i_mini].pop(0)
			for j in range(n):
				if j != i_mini:
					path[j] = stacks[j].pop()
			paths.append(path)
		for i in range(n):
			print(*[paths[j][i] for j in range(m)])
main()


t = int(input())
for hh in range(0, t):
	(n, m) = [int(x) for x in input().split()]
	li = []
	mat = []
	ans = []
	for i in range(0, n):
		a = [int(x) for x in input().split()]
		a.sort()
		mat.append(a)
	while 1:
		li = []
		mn = 1000000000
		for i in range(0, n):
			if mat[i][0] < mn:
				mn = mat[i][0]
				mnidx = i
		for i in range(0, n):
			if i == mnidx:
				li.append(mat[i][0])
				mat[i].pop(0)
			else:
				li.append(mat[i][-1])
				sz = len(mat[i])
				mat[i].pop(sz - 1)
		ans.append(li)
		if len(mat[0]) == 0:
			break
	finalans = []
	for i in range(0, len(ans[0])):
		li = []
		for j in range(0, len(ans)):
			li.append(ans[j][i])
		finalans.append(li)
	for i in range(0, len(finalans)):
		print(*finalans[i])


t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().split()))
	mp = []
	res = [[0 for k in range(m)] for j in range(n)]
	for j in range(n):
		mp.append(list(map(int, input().split())))
	for k in range(m):
		minmp = [min(mpp) for mpp in mp]
		kind = minmp.index(min(minmp))
		for kk in range(n):
			if kk == kind:
				res[kk][k] = min(mp[kk])
				mp[kk].remove(min(mp[kk]))
			else:
				res[kk][k] = max(mp[kk])
				mp[kk].remove(max(mp[kk]))
	[print(*ress) for ress in res]


import heapq
t = int(input())

def print_list(l):
	for element in l[:-1]:
		print(element, end=' ')
	print(l[len(l) - 1])
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	b = []
	b_copy = []
	for i in range(n):
		l = list(map(int, input().split()))
		b.append(l)
		b_copy.append(l.copy())
	heap = b_copy[0]
	heapq.heapify(heap)
	for row in b_copy[1:]:
		for ele in row:
			heapq.heappush(heap, ele)
	smallest = dict()
	for i in range(m):
		x = heapq.heappop(heap)
		if x in smallest.keys():
			smallest[x] += 1
		else:
			smallest.setdefault(x, 1)
	del b_copy
	index = 0
	for i in range(len(b)):
		small = []
		large = []
		for element in b[i]:
			if element in smallest.keys() and smallest[element] > 0:
				small.append(element)
				smallest[element] -= 1
			else:
				large.append(element)
		b[i] = large[:index] + small + large[index:]
		index += len(small)
	for row in b:
		print_list(row)


tc = int(input())
for _ in range(tc):
	(n, m) = map(int, input().split())
	l = []
	x = []
	for i in range(n):
		l.append(list(map(int, input().split())))
		for j in range(m):
			x.append((l[-1][j], i, j))
	x.sort()
	mat = [[0] * m for _ in range(n)]
	for (a, b, c) in x[:m]:
		mat[b][c] = 1
	copy = []
	curr = 0
	for i in range(n):
		y = []
		hold = []
		for j in range(m):
			if mat[i][j]:
				hold.append(l[i][j])
			else:
				y.append(l[i][j])
		for z in hold:
			y.insert(curr, z)
			curr += 1
		copy.append(y)
	for i in copy:
		print(*i)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	b = []
	caminos = []
	for i in range(n):
		b.append(list(map(int, input().split())))
		caminos.extend(b[i])
	resp = [[0] * m for _ in range(n)]
	caminos.sort()
	for i in b:
		i.sort()
	for j in range(m):
		mejor = caminos[0]
		band = False
		for i in range(n):
			if b[i][0] == mejor and (not band):
				caminos.pop(0)
				b[i].pop(0)
				band = True
				resp[i][j] = mejor
			else:
				peor = b[i][-1]
				caminos.pop(-1)
				b[i].pop(-1)
				resp[i][j] = peor
	for i in range(n):
		for j in range(m):
			print(resp[i][j], end=' ')
		print()


for t in range(int(input())):
	(n, m) = map(int, input().split())
	b = [list(map(int, input().split())) for _ in range(n)]
	grid = [(i, j) for i in range(n) for j in range(m)]
	for k in range(m):
		(x, y) = min(grid, key=lambda x: b[x[0]][x[1]])
		grid.remove((x, k))
		(b[x][y], b[x][k]) = (b[x][k], b[x][y])
	for l in b:
		print(' '.join(map(str, l)))


from heapq import heappush, heappop, heapify
from collections import deque
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	mat = []
	for i in range(n):
		v = list(map(int, input().split()))
		mat.append(v)
	hp = []
	for i in range(n):
		for j in range(m):
			hp.append((mat[i][j], i, j))
	heapify(hp)
	vis = [False for i in range(m)]
	idx = 0
	dq = deque()
	for i in range(m):
		ele = heappop(hp)
		if vis[ele[2]] == False:
			vis[ele[2]] = True
		else:
			dq.append(ele)
	l = len(dq)
	for i in range(l):
		ele = dq.popleft()
		if vis[ele[2]] == False:
			vis[ele[2]] = True
		else:
			while idx < m and vis[idx]:
				idx += 1
			val = ele[0]
			x = ele[1]
			y = ele[2]
			temp = mat[x][idx]
			mat[x][idx] = val
			mat[x][y] = temp
			vis[idx] = True
			idx += 1
	for i in range(n):
		for j in range(m):
			print(mat[i][j], end=' ')
		print()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	G = [list(sorted(map(int, input().split()))) for i in range(n)]
	mins = [[10 ** 9, i] for i in range(m)]
	for i in range(n):
		o = list(sorted(mins, reverse=True))
		ans = [0] * m
		for j in range(m):
			mins[o[j][1]][0] = min(o[j][0], G[i][j])
			ans[o[j][1]] = G[i][j]
		print(*ans)


from sys import stdin
from collections import deque
input = lambda : stdin.readline().strip()
for _ in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	lst = []
	ans = []
	for i in range(0, n):
		lst.append([int(i) for i in input().split()])
		ans.append([0 for i in range(0, m)])
	lst3 = []
	for i in lst:
		for j in i:
			lst3.append(j)
	lst3.sort()
	for i in range(0, m):
		for j in range(0, n):
			if lst3[i] in lst[j]:
				ans[j][i] = lst3[i]
				lst[j].remove(lst3[i])
				break
	for i in range(0, n):
		a = len(lst[i])
		for j in range(0, a):
			k = 0
			while k < m:
				if ans[i][k] == 0:
					ans[i][k] = lst[i][j]
					break
				k += 1
	for i in ans:
		print(*i)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	b = [list(map(int, input().split())) for _ in range(n)]
	x = []
	for i in range(n):
		for j in range(m):
			x.append([b[i][j], i, j])
	x.sort()
	ans = [[0] * m for _ in range(n)]
	for i in range(m):
		(b0, j, k) = x[i]
		b[j][k] = 0
		ans[j][i] = b0
	for i in range(n):
		k = 0
		for j in range(m):
			bij = b[i][j]
			if not bij:
				continue
			while ans[i][k]:
				k += 1
			ans[i][k] = bij
	for ansi in ans:
		print(*ansi)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arr = []
	final = []
	for x in range(n):
		temp = list(map(int, input().split()))
		final = [[item, x] for item in temp]
		for item in final:
			arr.append(item)
	arr.sort()
	ans = [[0 for x in range(m)] for y in range(n)]
	cnt = 0
	for (ind, item) in enumerate(arr):
		val = item[0]
		i = item[1]
		if cnt < m:
			ans[i][ind] = val
			cnt += 1
		else:
			break
	occ = {}
	for (val, row) in arr[m:]:
		if row in occ:
			occ[row].append(val)
		else:
			occ[row] = [val]
	for x in range(n):
		for y in range(m):
			if ans[x][y] == 0:
				ans[x][y] = occ[x].pop()
	for x in range(n):
		print(' '.join([str(ans[x][i]) for i in range(m)]))


t = int(input())
for _ in range(t):
	(n, m) = [int(s) for s in input().split()]
	b = []
	for _ in range(n):
		b.append([int(s) for s in input().split()])
	flat = [item for sublist in b for item in sublist]
	flat.sort()
	tr = flat[m - 1]
	tr_tot = 1
	for i in range(m - 2, -1, -1):
		if flat[i] == tr:
			tr_tot += 1
		else:
			break
	i = 0
	tr_cnt = 0
	for sub in b:
		sub.sort()
		for (j, v) in enumerate(sub):
			if v > tr or (v == tr and tr_cnt >= tr_tot):
				break
			if v == tr:
				tr_cnt += 1
		sub = sub[m - i:m] + sub[:m - i]
		i += j
		print(' '.join([str(s) for s in sub]))


R = lambda : map(int, input().split())
(t,) = R()
while t:
	t -= 1
	(n, m) = R()
	a = []
	b = []
	i = j = 0
	while i < n:
		a += zip(R(), [i] * m)
		b += ([0] * m,)
		i += 1
	for (x, i) in sorted(a):
		while b[i][j % m]:
			j += 1
		b[i][j % m] = x
		j += 1
	for r in b:
		print(*r)


try:
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		final = []
		for i in range(n):
			t = []
			for j in range(m):
				t.append(0)
			final.append(t)
		main = []
		for i in range(n):
			arr = list(map(int, input().split()))
			if i == 0:
				final[0] = arr
				main = arr.copy()
			else:
				temp_main = []
				for j in range(m):
					temp_main.append([main[j], j])
				temp_main = sorted(temp_main, key=lambda x: (x[0], x[1]))
				temp_main.reverse()
				arr.sort()
				for j in range(m):
					final[i][temp_main[j][1]] = arr[j]
				for j in range(m):
					main[temp_main[j][1]] = min(main[temp_main[j][1]], arr[j])
		for i in final:
			print(*i)
except EOFError:
	print(' ')


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	dist = []
	for i in range(n):
		temp = list(map(int, input().split()))
		temp.sort()
		dist.append(temp)
	left = [0] * n
	right = [m - 1] * n
	ans = [[] for i in range(n)]
	for k in range(m):
		(minVal, minIdx) = (2147483647, -1)
		for i in range(n):
			if dist[i][left[i]] < minVal:
				minVal = dist[i][left[i]]
				minIdx = i
		for i in range(n):
			if i != minIdx:
				ans[i].append(dist[i][right[i]])
				right[i] -= 1
			else:
				ans[i].append(dist[i][left[i]])
				left[i] += 1
	for row in ans:
		for i in row:
			print(i, end=' ')
		print()


def read_ints():
	return map(int, input().split())
for _ in range(int(input())):
	(n, m) = read_ints()
	A = [[num, cp] for cp in range(n) for num in read_ints()]
	A.sort()
	solution = [[0] * m for _ in range(n)]
	for i in range(m):
		assign = A.pop(0)
		checkpoint = assign[1]
		solution[checkpoint][i] = assign[0]
	while A:
		assign = A.pop(0)
		checkpoint = assign[1]
		for runner in range(m):
			if not solution[checkpoint][runner]:
				solution[checkpoint][runner] = assign[0]
				break
	for row in solution:
		print(*row)


from sys import *
import math
input = stdin.readline
I = int
R = range
listInput = lambda : list(map(int, input().strip().split()))
lineInput = lambda : map(int, input().strip().split())
sJoin = lambda a, sep: '{}'.format(sep).join(a)
arrJoin = lambda a, sep: '{}'.format(sep).join(map(str, a))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	for i in range(5, int(math.sqrt(n) + 1), 6):
		if n % i == 0 or n % (i + 2) == 0:
			return False
	return True

def main():
	for _ in R(I(input())):
		(n, m) = lineInput()
		ans = [[-1] * m for i in range(n)]
		pathAndRow = []
		for i in range(n):
			for j in listInput():
				pathAndRow.append((j, i))
		pathAndRow.sort()
		for i in range(m):
			ele = pathAndRow.pop(0)
			ans[ele[1]][i] = ele[0]
		while pathAndRow:
			ele = pathAndRow.pop(0)
			itr = 0
			while ans[ele[1]][itr] != -1:
				itr += 1
			ans[ele[1]][itr] = ele[0]
		for i in range(n):
			print(*ans[i])
main()


def divisors(M):
	d = []
	i = 1
	while M >= i ** 2:
		if M % i == 0:
			d.append(i)
			if i ** 2 != M:
				d.append(M // i)
		i = i + 1
	return d

def popcount(x):
	x = x - (x >> 1 & 1431655765)
	x = (x & 858993459) + (x >> 2 & 858993459)
	x = x + (x >> 4) & 252645135
	x = x + (x >> 8)
	x = x + (x >> 16)
	return x & 127

def eratosthenes(n):
	res = [0 for i in range(n + 1)]
	prime = set([])
	for i in range(2, n + 1):
		if not res[i]:
			prime.add(i)
			for j in range(1, n // i + 1):
				res[i * j] = 1
	return prime

def factorization(n):
	res = []
	for p in prime:
		if n % p == 0:
			while n % p == 0:
				n //= p
			res.append(p)
	if n != 1:
		res.append(n)
	return res

def euler_phi(n):
	res = n
	for x in range(2, n + 1):
		if x ** 2 > n:
			break
		if n % x == 0:
			res = res // x * (x - 1)
			while n % x == 0:
				n //= x
	if n != 1:
		res = res // n * (n - 1)
	return res

def ind(b, n):
	res = 0
	while n % b == 0:
		res += 1
		n //= b
	return res

def isPrimeMR(n):
	if n == 1:
		return 0
	d = n - 1
	d = d // (d & -d)
	L = [2, 3, 5, 7, 11, 13, 17]
	for a in L:
		t = d
		y = pow(a, t, n)
		if y == 1:
			continue
		while y != n - 1:
			y = y * y % n
			if y == 1 or t == n - 1:
				return 0
			t <<= 1
	return 1

def findFactorRho(n):
	from math import gcd
	m = 1 << n.bit_length() // 8
	for c in range(1, 99):
		f = lambda x: (x * x + c) % n
		(y, r, q, g) = (2, 1, 1, 1)
		while g == 1:
			x = y
			for i in range(r):
				y = f(y)
			k = 0
			while k < r and g == 1:
				ys = y
				for i in range(min(m, r - k)):
					y = f(y)
					q = q * abs(x - y) % n
				g = gcd(q, n)
				k += m
			r <<= 1
		if g == n:
			g = 1
			while g == 1:
				ys = f(ys)
				g = gcd(abs(x - ys), n)
		if g < n:
			if isPrimeMR(g):
				return g
			elif isPrimeMR(n // g):
				return n // g
			return findFactorRho(g)

def primeFactor(n):
	i = 2
	ret = {}
	rhoFlg = 0
	while i * i <= n:
		k = 0
		while n % i == 0:
			n //= i
			k += 1
		if k:
			ret[i] = k
		i += 1 + i % 2
		if i == 101 and n >= 2 ** 20:
			while n > 1:
				if isPrimeMR(n):
					(ret[n], n) = (1, 1)
				else:
					rhoFlg = 1
					j = findFactorRho(n)
					k = 0
					while n % j == 0:
						n //= j
						k += 1
					ret[j] = k
	if n > 1:
		ret[n] = 1
	if rhoFlg:
		ret = {x: ret[x] for x in sorted(ret)}
	return ret

def divisors(n):
	res = [1]
	prime = primeFactor(n)
	for p in prime:
		newres = []
		for d in res:
			for j in range(prime[p] + 1):
				newres.append(d * p ** j)
		res = newres
	res.sort()
	return res

def xorfactorial(num):
	if num == 0:
		return 0
	elif num == 1:
		return 1
	elif num == 2:
		return 3
	elif num == 3:
		return 0
	else:
		x = baseorder(num)
		return 2 ** x * ((num - 2 ** x + 1) % 2) + function(num - 2 ** x)

def xorconv(n, X, Y):
	if n == 0:
		res = [X[0] * Y[0] % mod]
		return res
	x = [digit[i] + X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	y = [Y[i] + Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	z = [digit[i] - X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	w = [Y[i] - Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	res1 = xorconv(n - 1, x, y)
	res2 = xorconv(n - 1, z, w)
	former = [(res1[i] + res2[i]) * inv for i in range(2 ** (n - 1))]
	latter = [(res1[i] - res2[i]) * inv for i in range(2 ** (n - 1))]
	former = list(map(lambda x: x % mod, former))
	latter = list(map(lambda x: x % mod, latter))
	return former + latter

def merge_sort(A, B):
	(pos_A, pos_B) = (0, 0)
	(n, m) = (len(A), len(B))
	res = []
	while pos_A < n and pos_B < m:
		(a, b) = (A[pos_A], B[pos_B])
		if a < b:
			res.append(a)
			pos_A += 1
		else:
			res.append(b)
			pos_B += 1
	res += A[pos_A:]
	res += B[pos_B:]
	return res

class UnionFindVerSize:

	def __init__(self, N):
		self._parent = [n for n in range(0, N)]
		self._size = [1] * N
		self.group = N

	def find_root(self, x):
		if self._parent[x] == x:
			return x
		self._parent[x] = self.find_root(self._parent[x])
		stack = [x]
		while self._parent[stack[-1]] != stack[-1]:
			stack.append(self._parent[stack[-1]])
		for v in stack:
			self._parent[v] = stack[-1]
		return self._parent[x]

	def unite(self, x, y):
		gx = self.find_root(x)
		gy = self.find_root(y)
		if gx == gy:
			return
		self.group -= 1
		if self._size[gx] < self._size[gy]:
			self._parent[gx] = gy
			self._size[gy] += self._size[gx]
		else:
			self._parent[gy] = gx
			self._size[gx] += self._size[gy]

	def get_size(self, x):
		return self._size[self.find_root(x)]

	def is_same_group(self, x, y):
		return self.find_root(x) == self.find_root(y)

class WeightedUnionFind:

	def __init__(self, N):
		self.parent = [i for i in range(N)]
		self.size = [1 for i in range(N)]
		self.val = [0 for i in range(N)]
		self.flag = True
		self.edge = [[] for i in range(N)]

	def dfs(self, v, pv):
		stack = [(v, pv)]
		new_parent = self.parent[pv]
		while stack:
			(v, pv) = stack.pop()
			self.parent[v] = new_parent
			for (nv, w) in self.edge[v]:
				if nv != pv:
					self.val[nv] = self.val[v] + w
					stack.append((nv, v))

	def unite(self, x, y, w):
		if not self.flag:
			return
		if self.parent[x] == self.parent[y]:
			self.flag = self.val[x] - self.val[y] == w
			return
		if self.size[self.parent[x]] > self.size[self.parent[y]]:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[x] += self.size[y]
			self.val[y] = self.val[x] - w
			self.dfs(y, x)
		else:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[y] += self.size[x]
			self.val[x] = self.val[y] + w
			self.dfs(x, y)

class Dijkstra:

	class Edge:

		def __init__(self, _to, _cost):
			self.to = _to
			self.cost = _cost

	def __init__(self, V):
		self.G = [[] for i in range(V)]
		self._E = 0
		self._V = V

	@property
	def E(self):
		return self._E

	@property
	def V(self):
		return self._V

	def add_edge(self, _from, _to, _cost):
		self.G[_from].append(self.Edge(_to, _cost))
		self._E += 1

	def shortest_path(self, s):
		import heapq
		que = []
		d = [10 ** 15] * self.V
		d[s] = 0
		heapq.heappush(que, (0, s))
		while len(que) != 0:
			(cost, v) = heapq.heappop(que)
			if d[v] < cost:
				continue
			for i in range(len(self.G[v])):
				e = self.G[v][i]
				if d[e.to] > d[v] + e.cost:
					d[e.to] = d[v] + e.cost
					heapq.heappush(que, (d[e.to], e.to))
		return d

def Z_algorithm(s):
	N = len(s)
	Z_alg = [0] * N
	Z_alg[0] = N
	i = 1
	j = 0
	while i < N:
		while i + j < N and s[j] == s[i + j]:
			j += 1
		Z_alg[i] = j
		if j == 0:
			i += 1
			continue
		k = 1
		while i + k < N and k + Z_alg[k] < j:
			Z_alg[i + k] = Z_alg[k]
			k += 1
		i += k
		j -= k
	return Z_alg

class BIT:

	def __init__(self, n, mod=0):
		self.BIT = [0] * (n + 1)
		self.num = n
		self.mod = mod

	def query(self, idx):
		res_sum = 0
		mod = self.mod
		while idx > 0:
			res_sum += self.BIT[idx]
			if mod:
				res_sum %= mod
			idx -= idx & -idx
		return res_sum

	def update(self, idx, x):
		mod = self.mod
		while idx <= self.num:
			self.BIT[idx] += x
			if mod:
				self.BIT[idx] %= mod
			idx += idx & -idx
		return

class dancinglink:

	def __init__(self, n, debug=False):
		self.n = n
		self.debug = debug
		self._left = [i - 1 for i in range(n)]
		self._right = [i + 1 for i in range(n)]
		self.exist = [True for i in range(n)]

	def pop(self, k):
		if self.debug:
			assert self.exist[k]
		L = self._left[k]
		R = self._right[k]
		if L != -1:
			if R != self.n:
				(self._right[L], self._left[R]) = (R, L)
			else:
				self._right[L] = self.n
		elif R != self.n:
			self._left[R] = -1
		self.exist[k] = False

	def left(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._left[res]
			if res == -1:
				break
			k -= 1
		return res

	def right(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._right[res]
			if res == self.n:
				break
			k -= 1
		return res

class SparseTable:

	def __init__(self, A, merge_func, ide_ele):
		N = len(A)
		n = N.bit_length()
		self.table = [[ide_ele for i in range(n)] for i in range(N)]
		self.merge_func = merge_func
		for i in range(N):
			self.table[i][0] = A[i]
		for j in range(1, n):
			for i in range(0, N - 2 ** j + 1):
				f = self.table[i][j - 1]
				s = self.table[i + 2 ** (j - 1)][j - 1]
				self.table[i][j] = self.merge_func(f, s)

	def query(self, s, t):
		b = t - s + 1
		m = b.bit_length() - 1
		return self.merge_func(self.table[s][m], self.table[t - 2 ** m + 1][m])

class BinaryTrie:

	class node:

		def __init__(self, val):
			self.left = None
			self.right = None
			self.max = val

	def __init__(self):
		self.root = self.node(-10 ** 15)

	def append(self, key, val):
		pos = self.root
		for i in range(29, -1, -1):
			pos.max = max(pos.max, val)
			if key >> i & 1:
				if pos.right is None:
					pos.right = self.node(val)
					pos = pos.right
				else:
					pos = pos.right
			elif pos.left is None:
				pos.left = self.node(val)
				pos = pos.left
			else:
				pos = pos.left
		pos.max = max(pos.max, val)

	def search(self, M, xor):
		res = -10 ** 15
		pos = self.root
		for i in range(29, -1, -1):
			if pos is None:
				break
			if M >> i & 1:
				if xor >> i & 1:
					if pos.right:
						res = max(res, pos.right.max)
					pos = pos.left
				else:
					if pos.left:
						res = max(res, pos.left.max)
					pos = pos.right
			elif xor >> i & 1:
				pos = pos.right
			else:
				pos = pos.left
		if pos:
			res = max(res, pos.max)
		return res

def solveequation(edge, ans, n, m):
	x = [0] * m
	used = [False] * n
	for v in range(n):
		if used[v]:
			continue
		y = dfs(v)
		if y != 0:
			return False
	return x

	def dfs(v):
		used[v] = True
		r = ans[v]
		for (to, dire, id) in edge[v]:
			if used[to]:
				continue
			y = dfs(to)
			if dire == -1:
				x[id] = y
			else:
				x[id] = -y
			r += y
		return r

class Matrix:
	mod = 10 ** 9 + 7

	def set_mod(m):
		Matrix.mod = m

	def __init__(self, L):
		self.row = len(L)
		self.column = len(L[0])
		self._matrix = L
		for i in range(self.row):
			for j in range(self.column):
				self._matridigit[i][j] %= Matrix.mod

	def __getitem__(self, item):
		if type(item) == int:
			raise IndexError('you must specific row and column')
		elif len(item) != 2:
			raise IndexError('you must specific row and column')
		(i, j) = item
		return self._matridigit[i][j]

	def __setitem__(self, item, val):
		if type(item) == int:
			raise IndexError('you must specific row and column')
		elif len(item) != 2:
			raise IndexError('you must specific row and column')
		(i, j) = item
		self._matridigit[i][j] = val

	def __add__(self, other):
		if (self.row, self.column) != (other.row, other.column):
			raise SizeError('sizes of matrixes are different')
		res = [[0 for j in range(self.column)] for i in range(self.row)]
		for i in range(self.row):
			for j in range(self.column):
				res[i][j] = self._matridigit[i][j] + other._matridigit[i][j]
				res[i][j] %= Matrix.mod
		return Matrix(res)

	def __sub__(self, other):
		if (self.row, self.column) != (other.row, other.column):
			raise SizeError('sizes of matrixes are different')
		res = [[0 for j in range(self.column)] for i in range(self.row)]
		for i in range(self.row):
			for j in range(self.column):
				res[i][j] = self._matridigit[i][j] - other._matridigit[i][j]
				res[i][j] %= Matrix.mod
		return Matrix(res)

	def __mul__(self, other):
		if type(other) != int:
			if self.column != other.row:
				raise SizeError('sizes of matrixes are different')
			res = [[0 for j in range(other.column)] for i in range(self.row)]
			for i in range(self.row):
				for j in range(other.column):
					temp = 0
					for k in range(self.column):
						temp += self._matridigit[i][k] * other._matrix[k][j]
					res[i][j] = temp % Matrix.mod
			return Matrix(res)
		else:
			n = other
			res = [[n * self._matridigit[i][j] % Matrix.mod for j in range(self.column)] for i in range(self.row)]
			return Matrix(res)

	def __pow__(self, m):
		if self.column != self.row:
			raise MatrixPowError('the size of row must be the same as that of column')
		n = self.row
		res = Matrix([[int(i == j) for i in range(n)] for j in range(n)])
		while m:
			if m % 2 == 1:
				res = res * self
			self = self * self
			m //= 2
		return res

	def __str__(self):
		res = []
		for i in range(self.row):
			for j in range(self.column):
				res.append(str(self._matridigit[i][j]))
				res.append(' ')
			res.append('\n')
		res = res[:len(res) - 1]
		return ''.join(res)
import sys, random, bisect
from collections import deque, defaultdict
from heapq import heapify, heappop, heappush
from itertools import permutations
from math import gcd, log
input = lambda : sys.stdin.buffer.readline()
mi = lambda : map(int, input().split())
li = lambda : list(mi())
for _ in range(int(input())):
	(n, m) = mi()
	res = [(10 ** 17, i) for i in range(m)]
	ans = [[] for i in range(m)]
	for i in range(n):
		b = li()
		b.sort(reverse=True)
		for j in range(m):
			idx = res[j][1]
			ans[idx].append(b[j])
			res[j] = (min(res[j][0], b[j]), res[j][1])
		res.sort()
	for i in range(n):
		tmp = [ans[j][i] for j in range(m)]
		print(*tmp)


for t in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(0, n):
		a = list(map(int, input().split()))
		if i == 0:
			a.sort()
			l.append(a)
		else:
			a.sort()
			l.append(a)
	res = []
	for j in range(0, m):
		min1 = 1000000000
		ind1 = -1
		for i in range(0, n):
			if l[i][0] < min1:
				min1 = l[i][0]
				ind1 = i
		a = []
		for i in range(0, n):
			if ind1 == i:
				a.append(l[i][0])
				l[i].pop(0)
			else:
				a.append(l[i][-1])
				l[i].pop()
		res.append(a)
	for i in range(0, n):
		for j in range(0, m):
			print(res[j][i], end=' ')
		print()


from pprint import pprint

def p(rows):
	for row in rows:
		for col in row:
			print(col, end=' ')
		print()

def main():
	T = int(input())
	for t in range(T):
		(n, m) = [int(v) for v in input().split()]
		rows = [[int(v) for v in input().split()] for i in range(n)]
		triples = []
		for i in range(n):
			for j in range(m):
				triples.append((rows[i][j], i, j))
		triples = sorted(triples, key=lambda x: x[0])
		remains = [list() for _ in range(n)]
		for i in range(n):
			remains[i].extend(rows[i])
		for i in range(n):
			for j in range(m):
				rows[i][j] = -1
		for r in range(m):
			(v, i, j) = triples[r]
			rows[i][r] = v
			remains[i].remove(v)
		for i in range(n):
			for j in range(m):
				if rows[i][j] == -1:
					rows[i][j] = remains[i].pop()
		p(rows)
main()


T = int(input())
for t in range(T):
	(n, m) = map(int, input().split())
	g = []
	a = []
	z = []
	for i in range(n):
		l = list(map(int, input().split()))
		a.append(l)
		z = z + l
	li = []
	for i in range(len(z)):
		li.append([z[i], i])
	li.sort()
	sort_index = []
	for x in li:
		sort_index.append(x[1])
	for i in range(m):
		g.append(sort_index[i] // m)
	c = 0
	q = []
	for i in range(n):
		if g.count(i) != 0:
			q = a[i].copy()
			q.sort()
			answer = q[len(q) - c:] + q[:len(q) - c]
			print(*answer, sep=' ')
			c = c + g.count(i)
		else:
			print(*a[i], sep=' ')


import sys
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		(N, M) = [int(x) for x in input().split()]
		B = [[int(x) for x in input().split()] for _ in range(N)]
		memo = []
		ans = [[0] * M for j in range(N)]
		for (i, b) in enumerate(B[0]):
			memo.append([b, i])
			ans[0][i] = b
		for i in range(1, N):
			memo.sort(reverse=True)
			j = 0
			for b in sorted(B[i]):
				ans[i][memo[j][1]] = b
				memo[j][0] = min(memo[j][0], b)
				j += 1
		for aa in ans:
			print(*aa)
main()


from decimal import Decimal
import collections as coll
import sys
import math as mt
import random as rd
import bisect as bi
import time
sys.setrecursionlimit(1000000)

def uno():
	return int(sys.stdin.readline().strip())

def dos():
	return sys.stdin.readline().strip()

def tres():
	return map(int, sys.stdin.readline().strip().split())

def cuatro():
	return sys.stdin.readline().strip().split()
for _ in range(uno()):
	(n, m) = tres()
	b = []
	for i in range(n):
		b.append(list(tres()))
	d = []
	for i in range(n):
		for j in b[i]:
			d.append([j, i])
	d.sort()
	b = [[-1 for i in range(m)] for j in range(n)]
	a = [0] * n
	for i in range(m):
		b[d[i][1]][i] = d[i][0]
	for i in range(m, m * n):
		while b[d[i][1]][a[d[i][1]]] != -1:
			a[d[i][1]] += 1
		b[d[i][1]][a[d[i][1]]] = d[i][0]
		a[d[i][1]] += 1
	for i in range(n):
		print(*b[i])


t = int(input())
for case in range(1, t + 1):
	(n, m) = [int(x) for x in input().split(' ')]
	b = []
	for _ in range(n):
		b.append([int(x) for x in input().split(' ')])
	print(*b[0])
	tiredness = b[0].copy()
	for bb in b[1:]:
		bb.sort(reverse=True)
		tt = sorted(enumerate(tiredness), key=lambda x: x[1])
		aa = [-1] * m
		for (i, (j, tire)) in enumerate(tt):
			aa[j] = bb[i]
			tiredness[j] = min(bb[i], tire)
		print(*aa)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = []
	s = []
	indexs = [0 for i in range(n)]
	ans = [[0 for i in range(m)] for j in range(n)]
	for i in range(n):
		b = list(map(int, input().split()))
		a += [b]
		for j in range(m):
			s += [[b[j], i, j]]
	s.sort()
	mn = 0
	for i in range(m):
		val = s[i][0]
		li = s[i][1]
		ind = s[i][2]
		ans[li][mn] = val
		mn += 1
		a[li][ind] = 0
	for i in range(n):
		for j in range(m):
			y = a[i][j]
			if y != 0:
				for k in range(m):
					z = ans[i][k]
					if z == 0:
						ans[i][k] = y
						break
	for i in range(n):
		print(*ans[i])


for t in range(int(input())):
	(n, m) = map(int, input().split())
	paths = []
	for i in range(n):
		row = list(map(int, input().split()))
		for j in range(m):
			paths.append([row[j], i, j])
	paths.sort()
	order = []
	for i in range(n):
		order.append([-1 for i in range(m)])
	person = 0
	for (val, i, j) in paths:
		prev = person
		while order[i][person] != -1:
			person += 1
			person %= m
		order[i][person] = val
		person = (prev + 1) % m
	for i in range(n):
		for j in range(m):
			print(order[i][j], end=' ')
		print()


I = lambda : map(int, input().split())
for _ in [0] * int(input()):
	(n, m) = I()
	linit = list(I())
	linit.sort()
	print(*linit)
	l = [[linit[i], i] for i in range(m)]
	for i in range(1, n):
		x = list(I())
		x.sort(reverse=1)
		y = [0] * m
		k = 0
		for jj in range(m):
			y[l[jj][1]] = x[k]
			if l[jj][0] > x[k]:
				l[jj][0] = x[k]
			k = k + 1
		l.sort()
		print(*y)


for ii in range(int(input())):
	(n, m) = map(int, input().split())
	(a, z, d) = ([], [0] * n, [])
	for jj in range(n):
		d.append([0] * m)
	e = d[:]
	for jj in range(n):
		h = sorted(list(map(int, input().split())))
		a.append(h)
	for jj in range(m):
		(r, f) = (0, 10 ** 9)
		for kk in range(n):
			if m > z[kk]:
				if f > a[kk][z[kk]]:
					r = kk
					f = a[kk][z[kk]]
		e[r][jj] = 1
		d[r][jj] = a[r][z[r]]
		z[r] = 1 + z[r]
	for jj in range(n):
		for kk in range(m):
			if not e[jj][kk]:
				d[jj][kk] = a[jj][z[jj]]
				z[jj] = 1 + z[jj]
		print(*d[jj])


import heapq

def main():
	t = int(input())
	n = [0 for _ in range(t)]
	m = [0 for _ in range(t)]
	b = [None for _ in range(t)]
	for i in range(t):
		(n[i], m[i]) = map(int, input().split())
		b[i] = [[0 for _ in range(m[i])] for _ in range(n[i])]
		for j in range(n[i]):
			b[i][j] = list(map(int, input().split()))
	ans = [None for _ in range(t)]
	for i in range(t):
		ans[i] = [[-1 for _ in range(m[i])] for _ in range(n[i])]
		pque = []
		for j in range(n[i]):
			for k in range(m[i]):
				heapq.heappush(pque, (b[i][j][k], j, k))
		placement = [[-1 for _ in range(m[i])] for _ in range(n[i])]
		for j in range(m[i]):
			next = heapq.heappop(pque)
			placement[next[1]][next[2]] = j
		for j in range(n[i]):
			p = 0
			for k in range(m[i]):
				ans[i][j][p] = b[i][j][k]
				if placement[j][k] != -1:
					(ans[i][j][p], ans[i][j][placement[j][k]]) = (ans[i][j][placement[j][k]], ans[i][j][p])
				while ans[i][j][p] != -1:
					p += 1
					if p >= m[i]:
						break
	for i in range(t):
		for j in range(n[i]):
			print(' '.join([str(x) for x in ans[i][j]]))
main()


import sys

def input():
	return sys.stdin.readline().rstrip()

def input_split():
	return [int(i) for i in input().split()]
testCases = int(input())
answers = []
for _ in range(testCases):
	(n, m) = input_split()
	grid = []
	vals = []
	for i in range(n):
		grid.append(input_split())
	for i in range(n):
		for j in range(m):
			vals.append((grid[i][j], (i, j)))
	vals.sort()
	assig = [[-1 for _ in range(m)] for _ in range(n)]
	pending = [{} for i in range(n)]
	for i in range(n):
		for j in range(m):
			if grid[i][j] not in pending[i]:
				pending[i][grid[i][j]] = 0
			pending[i][grid[i][j]] += 1
	for (runner, (v, (i, j))) in enumerate(vals[:m]):
		assig[i][runner] = v
		pending[i][v] -= 1
		if pending[i][v] == 0:
			del pending[i][v]
	for runner in range(m):
		for checkpt in range(n):
			if assig[checkpt][runner] == -1:
				k = next(iter(pending[checkpt]))
				assig[checkpt][runner] = k
				pending[checkpt][k] -= 1
				if pending[checkpt][k] == 0:
					del pending[checkpt][k]
	for i in range(n):
		print(*assig[i], sep=' ')


t = int(input())
for t in range(t):
	(p, q) = map(int, input().split())
	lst = []
	d = {}
	for i in range(p):
		lst1 = list(map(int, input().split()))
		lst.append(lst1)
		j = 0
		while j < q:
			if lst1[j] in d:
				d[lst1[j]] += 1
			else:
				d[lst1[j]] = 1
			j += 1
	lst2 = []
	for i in d:
		q1 = d[i]
		for j in range(q1):
			lst2.append(i)
	lst2.sort()
	q1 = 0
	lst3 = []
	for i in range(q):
		l = []
		for l1 in lst:
			if q1 != 0:
				max1 = max(l1)
				l1.remove(max1)
				l.append(max1)
			elif lst2[i] in l1:
				l.append(lst2[i])
				l1.remove(lst2[i])
				q1 = 1
			else:
				max1 = max(l1)
				l1.remove(max1)
				l.append(max1)
		q1 = 0
		lst3.append(l)
	for i in range(p):
		for j in range(q):
			print(lst3[j][i], end=' ')
		print()


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	(n, m) = map(int, sys.stdin.readline().split())
	paths = []
	b = list(map(int, sys.stdin.readline().split()))
	for bi in b:
		paths.append([bi, [bi]])
	paths = sorted(paths)
	for _ in range(n - 1):
		b = list(map(int, sys.stdin.readline().split()))
		b = sorted(b, reverse=True)
		for i in range(len(b)):
			paths[i][0] = min(paths[i][0], b[i])
			paths[i][1].append(b[i])
		paths = sorted(paths)
	for i in range(n):
		for j in range(m):
			print(paths[j][1][i], end=' ')
		print()


t = int(input())
for w in range(t):
	inp = input().split()
	m = int(inp[1])
	n = int(inp[0])
	arr = []
	arr1 = []
	row = 0
	dp = [[False for i in range(m)] for j in range(n)]
	result = [[None for i in range(m)] for j in range(n)]
	for j in range(n):
		col = 0
		inp1 = []
		inp = input().split()
		for i in inp:
			inp1.append(int(i))
			arr1.append([int(i), row, col])
			col += 1
		arr.append(inp1)
		row += 1
	arr1.sort()
	i = 0
	column1 = 0
	while i < m:
		q = arr1[i]
		result[q[1]][column1] = q[0]
		dp[q[1]][q[2]] = True
		i += 1
		column1 += 1
	row = 0
	for i in range(len(arr)):
		arr2 = []
		for j in range(len(arr[0])):
			if dp[i][j] == False:
				arr2.append(arr[i][j])
		column = 0
		r = 0
		while column < m:
			if result[i][column] == None:
				result[i][column] = arr2[r]
				r += 1
			column += 1
	for i in result:
		for j in i:
			print(j, end=' ')
		print()


def readline():
	return map(int, input().split())

def solve(n, m, b):
	runners = []
	for __ in range(m):
		runner = []
		(shortest_i, __) = min(enumerate(b), key=lambda x: x[1])
		for (i, bi) in enumerate(b):
			runner.append(bi.pop(0) if i == shortest_i else bi.pop())
		runners.append(runner)
	assert all((not bi for bi in b))
	return zip(*runners)

def main():
	(t,) = readline()
	for __ in range(t):
		(n, m) = readline()
		b = [sorted(readline()) for __ in range(n)]
		ans = solve(n, m, b)
		for row in ans:
			print(*row)
main()


def ii():
	return int(input())

def li():
	return [int(i) for i in input().split()]
for t in range(ii()):
	(n, m) = li()
	b = []
	for i in range(n):
		temp = li()
		temp.sort()
		b.append(temp)
	ans = [[-1 for j in range(m)] for i in range(n)]
	for i in range(m):
		index = -1
		mini = 10000000000000
		for j in range(n):
			if b[j][0] < mini:
				mini = b[j][0]
				index = j
		for j in range(n):
			if j != index:
				ans[j][i] = b[j][-1]
				b[j].pop()
			else:
				ans[j][i] = b[j][0]
				b[j].remove(b[j][0])
	for i in ans:
		print(*i)


import sys
sys.setrecursionlimit(10000)
from collections import defaultdict
from heapq import heappush
from heapq import heappop
from math import ceil

def solve():
	(n, m) = map(int, input().split())
	d = {}
	for i in range(m):
		d[i] = []
	heap1 = []
	heap2 = []
	for i in range(m):
		heappush(heap2, (-float('inf'), i))
	for i in range(n):
		arr = list(map(int, input().split()))
		for i in arr:
			heappush(heap1, i)
		ans = []
		for i in range(m):
			a = heappop(heap1)
			(b, c) = heappop(heap2)
			d[c].append(a)
			ans.append([max(-a, b), c])
		for i in range(m):
			heappush(heap2, (ans[i][0], ans[i][1]))
	ans = []
	for j in range(n):
		ans = ''
		for i in range(m):
			ans += str(d[i][j])
			ans += ' '
		print(ans)
for i in range(int(input())):
	solve()


def print_list(l):
	for k in l:
		print(k, end=' ')
	print('')
T = int(input())
for t in range(T):
	A = []
	(n, m) = map(int, input().split())
	for i in range(n):
		A.append(list(map(int, input().split())))
	A[0].sort()
	ans = []
	print_list(A[0])
	for j in range(m):
		ans.append((A[0][j], j))
	ans.reverse()
	for i in range(1, n):
		A[i].sort()
		temp = [-1] * m
		for j in range(m):
			ans[j] = (min(A[i][j], ans[j][0]), ans[j][1])
			temp[ans[j][1]] = A[i][j]
		print_list(temp)
		ans.sort()
		ans.reverse()


def solve(n, m, b):
	res = [[0] * m for _ in range(n)]
	for (k, (l, i, j)) in enumerate(sorted(((b[i][j], i, j) for i in range(n) for j in range(m)))):
		if k == m:
			break
		b[i][j] = 0
		res[i][k] = l
	for i in range(n):
		j1 = j2 = 0
		while j1 < m and j2 < m:
			if res[i][j1] != 0:
				j1 += 1
				continue
			if b[i][j2] == 0:
				j2 += 1
				continue
			res[i][j1] = b[i][j2]
			j1 += 1
			j2 += 1
	return res
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	b = [list(map(int, input().split())) for _ in range(n)]
	res = solve(n, m, b)
	for e in res:
		print(*e)


def main():
	(N, M) = map(int, input().split())
	B = []
	for i in range(N):
		b = list(map(int, input().split()))
		for j in range(M):
			B.append([b[j], i])
	B.sort()
	Ans = [[-1] * M for _ in range(N)]
	for i in range(M):
		(Val, n) = B[i]
		Ans[n][i] = Val
		B[i][0] = -1
	Indexs = [0] * N
	for (Val, n) in B:
		if Val == -1:
			continue
		while Ans[n][Indexs[n]] != -1:
			Indexs[n] += 1
		Ans[n][Indexs[n]] = Val
	for i in Ans:
		print(*i)
T = int(input())
for _ in range(T):
	main()


for nt in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	curr = a[0]
	curr = sorted(curr)
	j = 0
	ans = []
	for i in curr:
		ans.append([i, i])
	while j < n - 1:
		nxt = a[j + 1]
		ans.sort(key=lambda x: x[0])
		nxt = sorted(nxt)[::-1]
		for i in range(m):
			ans[i][0] = min(ans[i][0], nxt[i])
			ans[i].append(nxt[i])
		j += 1
	f = []
	for i in range(1, n + 1):
		f.append([])
		for j in range(m):
			f[-1].append(ans[j][i])
	for i in f:
		print(*i)


import heapq
T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	paths = []
	for i in range(N):
		row = list(map(int, input().split()))
		for j in range(M):
			paths.append((row[j], i, j))
	paths.sort()
	assign = []
	for _ in range(N):
		assign.append([-1 for _ in range(M)])
	person = 0
	for (value, i, j) in paths:
		prev = person
		while assign[i][person] != -1:
			person += 1
			person %= M
		assign[i][person] = value
		person = (prev + 1) % M
	for i in range(N):
		for j in range(M):
			print(assign[i][j], end=' ')
		print()


import copy
from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
	(n, m) = map(int, stdin.readline().split())
	b = [[int(x) for x in input().split()] for _ in range(n)]
	a = []
	for i in range(n):
		b[i].sort()
	for x in b:
		for x0 in x:
			a += [x0]
	a.sort()
	a = a[:m]
	d = {}
	for x in a:
		d[x] = d.get(x, 0) + 1
	i = 0
	for lst in b:
		if lst[0] not in a:
			print(*lst)
		else:
			j = 0
			try:
				while d[lst[j]] > 0:
					d[lst[j]] -= 1
					j += 1
			except:
				pass
			ans = [-1] * m
			for i0 in range(i, m):
				ans[i0] = lst[i0 - i]
			for i0 in range(i):
				ans[i0] = lst[m - i0 - 1]
			i += j
			print(*ans)


trials = int(input())
while trials > 0:
	trials -= 1
	(n, m) = input().split(' ')
	(n, m) = (int(n), int(m))
	x = 0
	r = 0
	while r != n:
		r += 1
		b = list(input().split(' '))
		globals()['i' + f'{x + 1}'] = list(map(int, b))
		x += 1
	l = []
	z = 1
	for i in i1:
		l.append((i,))
	while z != n:
		l.sort(key=lambda x: min(x))
		globals()['i' + f'{z + 1}'].sort(reverse=True)
		k = 0
		for i in globals()['i' + f'{z + 1}']:
			l[k] += (i,)
			k += 1
		z += 1
	p = 0
	for i in l[0]:
		for i in l:
			print(i[p], end=' ')
		p += 1
		print()


import sys
from collections import deque

def rl():
	return sys.stdin.readline().strip()

def rl_types(types):
	str_list = [x for x in sys.stdin.readline().strip().split(' ')]
	return [types[i](str_list[i]) for i in range(len(str_list))]

def pr(something):
	sys.stdout.write(str(something) + '\n')

def pra(array):
	sys.stdout.write(' '.join([str(x) for x in array]) + '\n')

def solve(bvals, nrunners):
	tiredness = 0
	paths = []
	for ri in range(nrunners):
		mn = min([opts[0] for opts in bvals])
		n = len(bvals)
		curp = []
		found = False
		for i in range(n):
			if found:
				curp.append(bvals[i].pop())
			elif bvals[i][0] == mn:
				curp.append(bvals[i].popleft())
				found = True
			else:
				curp.append(bvals[i].pop())
		paths.append(curp)
	return paths
NT = int(rl())
for ti in range(NT):
	(n, m) = [int(x) for x in rl().split(' ')]
	bvals = []
	for _ in range(n):
		opts = deque(sorted([int(x) for x in rl().split(' ')]))
		bvals.append(opts)
	paths = solve(bvals, m)
	for j in range(n):
		pra([paths[i][j] for i in range(m)])


import sys, os.path
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		temp = list(map(int, input().split()))
		temp.sort()
		l.append(temp)
	for i in range(len(l)):
		l[i].sort()
	ans = [[] for i in range(n)]
	for i in range(m):
		temp = []
		ind = 0
		m1 = l[0][0]
		for j in range(1, n):
			if l[j][0] < m1:
				ind = j
			m1 = min(m1, l[j][0])
		for j in range(n):
			if j == ind:
				temp.append(l[j][0])
				l[j].pop(0)
			else:
				temp.append(l[j][-1])
				l[j].pop(-1)
		for k in range(len(temp)):
			ans[k].append(temp[k])
	for i in range(n):
		print(*ans[i])


from functools import reduce

def solve(n, m, B):
	B_f = reduce(lambda a, b: a + b, B)
	B_f = [[v, i] for (i, v) in enumerate(B_f)]
	B_f = sorted(B_f, key=lambda n: n[0])
	min_key = {}
	for i in range(m):
		(v, j) = B_f[i]
		min_key[j] = i
	arr = [[0] * m for _ in range(n)]
	for i in range(n):
		for j in range(m):
			if i * m + j in min_key:
				arr[i][min_key[i * m + j]] = B[i][j]
	for i in range(n):
		idx = 0
		for j in range(m):
			if i * m + j in min_key:
				continue
			else:
				while True:
					if idx >= m - 1 or arr[i][idx] == 0:
						break
					idx += 1
				arr[i][idx] = B[i][j]
	return arr

def main():
	ans = []
	t = int(input())
	for _ in range(t):
		(n, m) = list(map(int, input().split(' ')))
		B = [list(map(int, input().split(' '))) for i in range(n)]
		ans.append(solve(n, m, B))
	for arr in ans:
		for a in arr:
			print(' '.join(list(map(str, a))))
main()


ans = []
tests = int(input())
for test in range(tests):
	int_input = [int(x) for x in input().split(' ')]
	n = int_input[0]
	m = int_input[1]
	paths = []
	for i in range(n):
		path = sorted([int(x) for x in input().split(' ')])
		paths.append(path)
	checkpoints = [[] for x in paths]
	for j in range(m):
		min_val = min(range(n), key=lambda x: paths[x][0])
		for i in range(len(paths)):
			if i == min_val:
				checkpoints[i].append(paths[i].pop(0))
			else:
				checkpoints[i].append(paths[i].pop())
	for t in checkpoints:
		ans_str = ''
		for i in t:
			ans_str += str(i) + ' '
		ans.append(ans_str)
for i in ans:
	print(i)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	b = []
	for i in range(n):
		b.append(list(map(int, input().split())))
	arr = []
	for i in range(n):
		for j in range(m):
			arr.append((b[i][j], i))
	arr.sort()
	l = arr[:m]
	r = arr[m:]
	x = [[] for i in range(n)]
	for i in r:
		x[i[1]].append(i[0])
	ans = [[] for i in range(n)]
	while len(l):
		p = l.pop()
		for i in range(n):
			if i != p[1]:
				ans[i].append(x[i].pop())
			else:
				ans[i].append(p[0])
	for i in range(n):
		print(*ans[i])


import sys
input = sys.stdin.readline

def main():
	(n, m) = map(int, input().split())
	lst = []
	for i in range(n):
		bs = list(map(int, input().split()))
		for b in bs:
			lst.append((b, i))
	lst.sort()
	ans = [[-1] * m for _ in range(n)]
	for j in range(m):
		(b, i) = lst[j]
		ans[i][j] = b
	pos = [0] * n
	for (b, i) in lst[m:]:
		while ans[i][pos[i]] != -1:
			pos[i] += 1
		ans[i][pos[i]] = b
		pos[i] += 1
	for row in ans:
		print(*row)
for _ in range(int(input())):
	main()


import os
import sys
from collections import Counter
from io import BytesIO, IOBase
from math import gcd, inf, sqrt, ceil, floor

def lcm(a, b):
	return a * b // gcd(a, b)

def sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(sqrt(MAXN))):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def getFactorization(x):
	ret = set()
	while x != 1:
		ret.add(spf[x])
		x = x // spf[x]
	return ret

def printDivisors(n):
	i = 2
	z = [1, n]
	while i <= sqrt(n):
		if n % i == 0:
			if n / i == i:
				z.append(i)
			else:
				z.append(i)
				z.append(n // i)
		i = i + 1
	return z

def create(n, x, f):
	pq = len(bin(n)[2:])
	if f == 0:
		tt = min
	else:
		tt = max
	dp = [[inf] * n for _ in range(pq)]
	dp[0] = x
	for i in range(1, pq):
		for j in range(n - (1 << i) + 1):
			dp[i][j] = tt(dp[i - 1][j], dp[i - 1][j + (1 << i - 1)])
	return dp

def enquiry(l, r, dp, f):
	if l > r:
		return inf if not f else -inf
	if f == 1:
		tt = max
	else:
		tt = min
	pq1 = len(bin(r - l + 1)[2:]) - 1
	return tt(dp[pq1][l], dp[pq1][r - (1 << pq1) + 1])

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	x = []
	for i in range(2, n + 1):
		if prime[i]:
			x.append(i)
	return x

def main():
	for i in range(int(input())):
		(n, m) = map(int, input().split())
		a = []
		matx = []
		for j in range(n):
			matx.append([])
			c = 0
			for p in input().split():
				matx[-1].append(int(p))
				a.append((int(p), j, c))
				c += 1
		a.sort()
		an = [[-1] * m for j in range(n)]
		for j in range(m):
			an[a[j][1]][j] = a[j][0]
			matx[a[j][1]][a[j][2]] = -1
		for j in range(n):
			q = 0
			for p in range(m):
				if an[j][p] == -1:
					while matx[j][q] == -1:
						q += 1
					an[j][p] = matx[j][q]
					matx[j][q] = -1
		for j in range(n):
			for p in range(m):
				print(an[j][p], end=' ')
			print()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from sys import stdin, stdout
import sys
import math
import itertools
from collections import defaultdict
sys.setrecursionlimit(10 ** 6)

def shortrunner(barr, n, m):
	paths = []
	runway = {}
	c = 0
	for ckpt in barr:
		runway[c] = []
		for i in ckpt:
			paths.append(i)
		c += 1
	runner = 1
	while runner <= m:
		a = min(paths)
		paths = []
		run = []
		c = 0
		covered = 0
		for ckpt in barr:
			b = min(ckpt)
			if b == a and covered == 0:
				ckpt.remove(b)
				covered = 1
			else:
				b = max(ckpt)
				ckpt.remove(b)
			for i in ckpt:
				paths.append(i)
			runway[c].append(b)
			c += 1
		runner += 1
	return runway

def main():
	t = int(stdin.readline().strip())
	for i in range(1, t + 1):
		(n, m) = map(int, stdin.readline().split())
		barr = []
		for j in range(n):
			arr = [int(x) for x in stdin.readline().split()]
			barr.append(arr)
		ans = shortrunner(barr, n, m)
		for i in ans.values():
			print(*i)
main()


from copy import deepcopy
from collections import defaultdict, deque
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	edges = []
	for i in range(n):
		edges.append(list(map(int, input().split())))
	all_ = []
	for i in range(n):
		for j in range(m):
			all_.append((edges[i][j], i, j))
	all_.sort(key=lambda x: x[0])
	req_all = all_[:m]
	temp_req = [0] * n
	for i in req_all:
		(val, row, col) = i
		temp_req[row] += 1
	tot_done = 0
	for i in range(n):
		if temp_req[i] != 0:
			deg = temp_req[i]
			edges[i].sort()
			t = deque(edges[i])
			t.rotate(tot_done)
			edges[i] = list(t)
			tot_done += deg
	for i in edges:
		print(*i)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		t = list(map(int, input().split()))
		for j in t:
			l.append([j, i])
	l.sort()
	ans = [[-1] * n for i in range(m)]
	visited = {}
	for i in range(m):
		for j in range(len(l)):
			if j not in visited:
				ans[i][l[j][1]] = l[j][0]
				visited[j] = None
				break
		cnt = 1
		for j in range(len(l) - 1, -1, -1):
			if j not in visited and ans[i][l[j][1]] == -1:
				ans[i][l[j][1]] = l[j][0]
				visited[j] = None
				cnt += 1
				if cnt == n:
					break
	for j in range(n):
		for i in range(m):
			print(ans[i][j], end=' ')
		print()


from io import BytesIO, IOBase
from math import sqrt
import sys, os
inpl = lambda : list(map(int, input().split()))
inpm = lambda : map(int, input().split())
inpi = lambda : int(input())
inp = lambda : input()
(rev, ra, l) = (reversed, range, len)
P = print
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def B(n):
	return bin(n).replace('0b', '')

def factors(n):
	arr = []
	for i in ra(2, int(sqrt(n)) + 1):
		if n % i == 0:
			arr.append(i)
			if i * i != n:
				arr.append(int(n / i))
	return arr

def dfs(arr, n):
	pairs = [[i + 1] for i in ra(n)]
	vis = [0] * (n + 1)
	for i in ra(l(arr)):
		pairs[arr[i][0] - 1].append(arr[i][1])
	pairs[arr[i][1] - 1].append(arr[i][0])
	comp = []
	for i in ra(n):
		stack = [pairs[i]]
		temp = []
		if vis[stack[-1][0]] == 0:
			while len(stack) > 0:
				if vis[stack[-1][0]] == 0:
					temp.append(stack[-1][0])
					vis[stack[-1][0]] = 1
					s = stack.pop()
					for j in s[1:]:
						if vis[j] == 0:
							stack.append(pairs[j - 1])
				else:
					stack.pop()
			comp.append(temp)
	return comp
from bisect import bisect_left as bl
from bisect import bisect_right as br
import sys, operator, math, operator
from collections import Counter
import random
tc = inpi()
while tc:
	tc -= 1
	(n, m) = inpm()
	li = []
	arr = []
	for i in ra(n):
		temp = inpl()
		arr.append(sorted(temp))
		for j in temp:
			li.append([j, i + 1])
	li.sort()
	c = [0] * n
	for i in range(m):
		c[li[i][1] - 1] += 1
	pref = [c[0]]
	for i in ra(1, len(c)):
		pref.append(pref[-1] + c[i])
	fin = []
	for i in ra(n):
		if i == 0:
			fin.append(arr[i])
		else:
			j = c[i]
			temp = []
			temp.extend(arr[i][j:j + pref[i - 1]])
			temp.extend(arr[i][:c[i]])
			temp.extend(arr[i][j + pref[i - 1]:])
			fin.append(temp)
	for i in fin:
		P(*i)


import heapq
import sys
from collections import *
from heapq import *
import math
import bisect

def input():
	return sys.stdin.readline()
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	mat = []
	for _ in range(n):
		row = sorted(list(map(int, input().split())))
		mat.append(row)
	ans = []
	dic = defaultdict(int)
	for _ in range(m):
		temp = []
		minn = 10 ** 18
		ind = -1
		for i in range(n):
			if mat[i][dic[i]] < minn:
				minn = mat[i][dic[i]]
				ind = i
		for j in range(n):
			if ind == j:
				temp.append(mat[j][dic[j]])
				dic[j] += 1
			else:
				temp.append(mat[j][-1])
				mat[j].pop()
		ans.append(temp)
	for i in range(n):
		temp1 = []
		for j in range(m):
			temp1.append(ans[j][i])
		print(*temp1)


import sys, io, os
try:
	Z = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
except:
	Z = lambda : sys.stdin.readline().encode()
Y = lambda : map(int, Z().split())
O = []
for _ in range(int(Z())):
	(n, m) = Y()
	b = []
	r = [[0] * m for i in range(n)]
	a = []
	for i in range(n):
		l = [*Y()]
		a.append(l)
		for j in range(m):
			b.append((l[j], i, j))
	b.sort()
	for i in range(m):
		(v, x, y) = b[i]
		r[x][i] = v
		a[x][y] = 0
	for i in range(n):
		p = 0
		for j in range(m):
			if a[i][j]:
				while r[i][p]:
					p += 1
				r[i][p] = a[i][j]
	O.append('\n'.join((' '.join(map(str, i)) for i in r)))
print('\n'.join(O))


import os
import sys
import time
import heapq
from io import BytesIO, IOBase

def main():
	t = i_input()
	for tt in range(t):
		(n, m) = li_input()
		O = [[0] * m for _ in range(n)]
		h = []
		for nn in range(n):
			for (j, b) in enumerate(li_input()):
				heapq.heappush(h, (b, nn))
		nex = [0] * n
		for j in range(m):
			(b, i) = heapq.heappop(h)
			O[i][j] = b
			nex[i] = (j + 1) % m
		for (b, i) in h:
			while O[i][nex[i]]:
				nex[i] = (nex[i] + 1) % m
			O[i][nex[i]] = b
			nex[i] = (nex[i] + 1) % m
		OO = [' '.join(map(str, O[i])) for i in range(n)]
		print('\n'.join(OO))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def i_input():
	return int(input())

def l_input():
	return input().split()

def li_input():
	return list(map(int, l_input()))

def il_input():
	return list(map(int, l_input()))
TT = time.time()
main()


t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	ll = []
	for i in range(n):
		l = [int(x) for x in input().split()]
		l.sort()
		ll.append(l)
	st = 0
	ans = [0] * m
	for i in range(n):
		if i == 0:
			print(*ll[i])
			ans = ll[i]
			for aa in range(m):
				ans[aa] = [aa, ans[aa]]
		else:
			ans = sorted(ans, key=lambda x: x[1])
			ans.reverse()
			y = [0] * m
			for aa in range(m):
				y[ans[aa][0]] = ll[i][aa]
			print(*y)
			for aa in range(m):
				ans[aa][1] = min(ans[aa][1], y[ans[aa][0]])


def solve(n, m, b, tot):
	indt = 0
	cols = []
	for i in range(m):
		col = [0] * n
		monmin = tot[indt]
		col[monmin[1]] = monmin[0]
		for j in range(n):
			if j != monmin[1]:
				col[j] = b[j].pop()
		cols.append(col)
		indt += 1
	for i in range(n):
		print(*[cols[j][i] for j in range(m)])
t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().split()))
	b = []
	tot = []
	for j in range(n):
		bb = list(map(int, input().split()))
		bb.sort()
		b.append(bb)
		tot += [(x, j) for x in bb]
	tot.sort()
	solve(n, m, b, tot)


for test in range(int(input())):
	(n, m) = map(int, input().split())
	(lst, arr) = ([[0] for i in range(n)], [])
	for i in range(n):
		temp = sorted(map(int, input().split()))
		arr.extend(temp)
		arr = sorted(arr)[:m]
		lst[i] = temp.copy()
	ind = 0
	for i in range(n):
		if arr:
			temp = []
			for j in range(m):
				if lst[i][j] in arr:
					temp.append(lst[i][j])
					arr.remove(lst[i][j])
			for j in temp:
				lst[i].remove(j)
			for j in temp:
				lst[i].insert(ind, j)
				ind += 1
	for i in lst:
		print(*i)


for iadxa in range(int(input())):
	(n, m) = map(int, input().split())
	b = [sorted(list(map(int, input().split()))) for i in range(n)]
	cur = [[b[0][i], i] for i in range(m)]
	print(*b[0])
	for i in b[1:]:
		out = [0] * m
		for j in range(m):
			out[cur[j][1]] = i[-j - 1]
		print(*out)
		for j in range(m):
			cur[j][0] = min(cur[j][0], i[-j - 1])
		cur.sort()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	c = []
	k = []
	d = {}
	for i in range(n):
		t = []
		d[i] = 0
		b = list(map(int, input().split()))
		a.append(list(b))
		for j in range(m):
			t.append(0)
			c.append((b[j], i, j))
		k.append(list(t))
	c.sort()
	for i in range(m):
		k[c[i][1]][i] = c[i][0]
	for i in range(m, len(c)):
		while k[c[i][1]][d[c[i][1]]] != 0:
			d[c[i][1]] += 1
		k[c[i][1]][d[c[i][1]]] = c[i][0]
	for i in range(n):
		print(*k[i])


def answer():
	(n, m) = list(map(int, input().split()))
	x = []
	y = [[] for i in range(n)]
	for i in range(n):
		temp = list(map(int, input().split()))
		temp = [[x, i] for x in temp]
		y[i].extend(temp)
		x.extend(temp)
	x.sort()
	z = [[x[i]] for i in range(m)]
	for i in range(m):
		where = z[i][0][-1]
		y[where].remove(z[i][0])
	ans = []
	for i in range(m):
		where = z[i][0][-1]
		for j in range(n):
			if j != where:
				z[i].append(y[j][0])
				y[j].remove(y[j][0])
	for i in range(len(z)):
		z[i].sort(key=lambda x: x[-1])
	for i in range(n):
		for j in range(m):
			print(z[j][i][0], end=' ')
		print()
for i in range(int(input())):
	answer()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [[]] * n
	b = []
	for i in range(n):
		a[i] = list(map(int, input().split()))
		a[i].sort()
		for x in a[i]:
			b.append((x, i))
	b.sort()
	cnt = [0] * n
	for i in range(m):
		cnt[b[i][1]] += 1
	s = 0
	for i in range(n):
		for j in range(m - s, m):
			print(a[i][j], end=' ')
		for j in range(m - s):
			print(a[i][j], end=' ')
		print()
		s += cnt[i]


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(sorted(map(int, input().split())))
	v = [[] for i in range(n)]
	for i in range(m):
		k = 0
		for j in range(1, n):
			if a[j][0] < a[k][0]:
				k = j
		for j in range(n):
			if k == j:
				v[j].append(a[j][0])
				a[j] = a[j][1:]
			else:
				v[j].append(a[j][-1])
				a[j] = a[j][:-1]
	for i in range(n):
		print(' '.join(map(str, v[i])))


import sys
r = sys.stdin.readline
for _ in range(int(r())):
	(N, M) = map(int, r().split())
	L = []
	a = []
	for i in range(N):
		k = sorted(list(map(int, r().split())))
		L.append(k)
		for j in k:
			a.append(j)
	a.sort()
	mx = a[M - 1]
	mcnt = M - a.index(mx)
	toidx = 0
	for i in range(N):
		k = toidx
		idx = 0
		while idx < M:
			if L[i][idx] < mx:
				idx += 1
				toidx += 1
			elif L[i][idx] == mx and mcnt > 0:
				idx += 1
				mcnt -= 1
				toidx += 1
			else:
				break
		for j in range(M - k, M):
			print(L[i][j], end=' ')
		for j in range(M - k):
			print(L[i][j], end=' ')
		print()


for testcase in range(int(input())):
	arr = [int(x) for x in input().split()]
	(n, mind) = (arr[0], arr[1])
	arr = []
	for i in range(n):
		li = [int(x) for x in input().split()]
		li.sort()
		arr.append(li)
	ans = [[-1 for j in range(mind)] for i in range(n)]
	s = set()
	for j in range(mind):
		if j in s:
			continue
		else:
			m = float('inf')
			for k in range(n):
				ele = arr[k]
				m1 = ele[0]
				if m1 < m:
					m = m1
					ind = k
			ans[ind][j] = m
			arr[ind].remove(m)
			s.add(j)
	for j in range(mind):
		for i in range(n):
			if ans[i][j] == -1:
				ans[i][j] = arr[i][-1]
				arr[i] = arr[i][:-1]
	for ele in ans:
		print(*ele)


def inputi():
	return int(input())

def inputli():
	return list(map(int, input().split(' ')))

def inputls():
	return list(map(str, input().split(' ')))

def print_list(lista):
	s = ''
	for i in lista[:-1]:
		s += str(i) + ' '
	s += str(lista[-1])
	return s

def solve():
	[n, m] = inputli()
	aux = []
	ans = [[] for i in range(n)]
	for i in range(n):
		b = inputli()
		b = sorted(b)
		aux.append(b)
	for i in range(m):
		minis = [aux[j][0] for j in range(n)]
		mini = min(minis)
		idx = minis.index(mini)
		ans[idx].append(mini)
		aux[idx].pop(0)
		for j in range(n):
			if idx != j:
				ans[j].append(aux[j].pop())
	for i in range(n):
		print(print_list(ans[i]))
	return 0
t = inputi()
for i in range(t):
	solve()


def ints():
	return map(int, input().split())
for _ in range(int(input())):
	(n, m) = ints()
	s = []
	for i in range(n):
		for j in ints():
			s.append([j, i])
	s.sort()
	res = [[0] * m for i in range(n)]
	for i in range(m):
		res[s[i][1]][i] = s[i][0]
	for i in range(m, n * m):
		for j in range(m):
			if not res[s[i][1]][j]:
				res[s[i][1]][j] = s[i][0]
				break
	for row in res:
		print(*row)


from sys import stdin, stdout

def INI():
	return int(stdin.readline())

def INL():
	return [int(_) for _ in stdin.readline().split()]

def INS():
	return stdin.readline()

def MOD():
	return pow(10, 9) + 7

def OPS(ans):
	stdout.write(str(ans) + '\n')

def OPL(ans):
	[stdout.write(str(_) + ' ') for _ in ans]
	stdout.write('\n')
for _ in range(INI()):
	(n, m) = INL()
	X = []
	for _ in range(n):
		X.append(sorted(INL()))
	for __ in range(m):
		i = 0
		x = float('inf')
		for _ in range(n):
			if X[_][__] < x:
				x = X[_][__]
				i = _
		for _ in range(n):
			if _ == i:
				pass
			else:
				X[_][__:] = [X[_][-1]] + X[_][__:m - 1]
	for _ in range(n):
		OPL(X[_])


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ans = []
	min_ln = []
	for i in range(n):
		m_len = sorted(map(int, input().split()))
		if i == 0:
			for j in range(m):
				min_ln.append([m_len[j], j])
			ans.append(m_len)
			min_ln.sort()
		else:
			temp = [0] * m
			for j in range(m - 1, -1, -1):
				if min_ln[m - 1 - j][0] > m_len[j]:
					min_ln[m - 1 - j][0] = m_len[j]
				temp[min_ln[m - 1 - j][1]] = m_len[j]
			ans.append(temp)
			min_ln.sort()
	for an in range(n):
		print(*ans[an])


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split(' '))
	lis = []
	min = [0 for i in range(m)]
	for i in range(n):
		x = list(map(int, input().split(' ')))
		if i == 0:
			lis.append(x)
			mini = lis[i].copy()
		else:
			y = x.copy()
			x.sort()
			temp = mini.copy()
			for i in range(len(mini)):
				y[temp.index(max(temp))] = x[i]
				temp[temp.index(max(temp))] = 0
			x = y.copy()
			lis.append(x)
			temp = [0] * len(mini)
			for i in range(len(temp)):
				if mini[i] > x[i]:
					mini[i] = x[i]
	for i in lis:
		for j in i:
			print(j, end=' ')
		print()


import math

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split(' '))
		j = []
		for _ in range(n):
			b = list(map(int, input().split(' ')))
			j.append(b)
		print(get(n, m, j))

def get(n, m, b):
	runners = []
	for i in range(m):
		res = []
		(minimum, indexm) = minx(b)
		temp = b[indexm]
		temp.remove(minimum)
		b[indexm] = temp
		for (index, val) in enumerate(b):
			if index == indexm:
				res.append(minimum)
			else:
				res.append(max(val))
				b = delet(b, max(val), index)
		runners.append(res)
	res = ''
	for i in range(len(runners[0])):
		for (iv, j) in enumerate(runners):
			res += str(j[i])
			if iv != len(runners) - 1:
				res += ' '
		res += '\n'
	return res.strip()

def delet(b, val, index):
	temp = b[index]
	temp.remove(val)
	b[index] = temp
	return b

def minx(a):
	last = min(a[0])
	index = 0
	for (v, i) in enumerate(a):
		if min(i) < last:
			index = v
			last = min(i)
	return (last, index)
main()


def mapit():
	temp = list(map(int, input().split()))
	return temp

def solution():
	(n, m) = mapit()
	paths = []
	main = []
	for i in range(n):
		temp = mapit()
		main += temp
		paths.append(temp)
	main.sort(reverse=True)
	ele = {}
	for i in main[-m:]:
		if i not in ele:
			ele[i] = 1
		else:
			ele[i] += 1
	cols = [i for i in range(m - 1, -1, -1)]
	for i in range(n):
		curr = []
		notused = []
		for j in range(m):
			if cols != [] and paths[i][j] in ele and ele[paths[i][j]]:
				curr.append(paths[i][j])
				ele[paths[i][j]] -= 1
			else:
				notused.append(paths[i][j])
		eleidx = set()
		while curr:
			col = cols.pop()
			eleidx.add(col)
			paths[i][col] = curr.pop()
		for j in range(m):
			if j not in eleidx:
				paths[i][j] = notused.pop()
	for i in range(n):
		print(*paths[i])
	return
t = int(input())
while t:
	t -= 1
	solution()


import sys
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	path = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
	prior = []
	for i in range(n):
		for j in path[i]:
			prior.append((j, i))
	prior = sorted(prior)
	res = [[0] * m for i in range(n)]
	check = 0
	i = 0
	while check < m:
		this = prior[i]
		res[this[1]][check] = this[0]
		check += 1
		path[this[1]].remove(this[0])
		i += 1
	for i in range(n):
		for j in range(m):
			if res[i][j] == 0:
				res[i][j] = path[i].pop()
	for i in range(n):
		print(*res[i])


I = lambda : [*map(int, input().split())]
for _ in ' ' * I()[0]:
	(n, b) = I()
	l = [sorted(I()) for i in range(n)]
	ans = [[] for i in range(n)]
	for i in range(b):
		m = int(2000000000.0)
		x = -1
		for j in range(n):
			if m > l[j][0]:
				m = l[j][0]
				x = j
		for j in range(n):
			if x == j:
				ans[j] += [l[j][0]]
				l[j].pop(0)
			else:
				ans[j] += [l[j][-1]]
				l[j].pop(-1)
	for i in ans:
		print(*i)


from collections import defaultdict, Counter
from math import log10
for i in range(int(input())):
	(n, m) = map(int, input().split())
	ans = [[-1 for j in range(m)] for k in range(n)]
	final = []
	for j in range(n):
		b = list(map(int, input().split()))
		for k in range(m):
			final.append((b[k], j))
	final.sort()
	pos = 0
	for j in range(m):
		ans[final[j][1]][pos] = final[j][0]
		pos += 1
	pos = m
	for k in range(m, len(final)):
		row = final[k][1]
		for col in range(0, m):
			if ans[row][col] == -1:
				ans[row][col] = final[k][0]
				break
	for j in ans:
		print(*j)


from collections import Counter
import math

def main():
	t = int(input())
	for _ in range(t):
		(n, m) = list(map(int, input().split()))
		b = []
		for _ in range(n):
			b.append(sorted(list(map(int, input().split()))))
		all = [0] * n
		maxi = 10000000000
		mini = maxi
		for i in range(0, m):
			mini = maxi
			for j in range(n):
				if mini > b[j][all[j]]:
					mini = b[j][all[j]]
					temp = j
			for k in range(m - i - 1):
				b[temp][k] = b[temp][k + 1]
			b[temp][m - i - 1] = mini
		for i in range(n):
			s = ''
			for j in range(m):
				s += str(b[i][j]) + ' '
			print(s)
main()


T = int(input())
for case in range(T):
	(n, m) = map(int, input().split())
	stacks = [sorted(map(int, input().split())) for i in range(n)]
	paths = []
	for i in range(m):
		minis = []
		for i in range(n):
			minis.append(stacks[i][0])
		i_mini = minis.index(min(minis))
		path = [0] * n
		path[i_mini] = stacks[i_mini].pop(0)
		for j in range(n):
			if j != i_mini:
				path[j] = stacks[j].pop()
		paths.append(path)
	for i in range(n):
		p = [paths[j][i] for j in range(m)]
		print(*p)


def main():
	t = int(input())
	for i in range(t):
		s()

def s():
	(n, m) = map(int, input().split())
	a = []
	ans = [[] for i in range(n)]
	mins = []
	for i in range(n):
		a.append(list(map(int, input().split())))
		a[-1].sort()
	while len(a[0]) != 0:
		for i in range(n):
			mins.append(a[i][0])
		mn = mins.index(min(mins))
		ans[mn].append(a[mn].pop(0))
		mins.pop(mn)
		for i in range(n):
			if i != mn:
				ans[i].append(a[i].pop())
		mins = []
	for i in range(n):
		for j in range(m):
			print(ans[i][j], end=' ')
		print()
	ans = 0
	return ()
main()


test_cases = int(input())
for test_case in range(test_cases):
	(n, m) = list(map(int, input().split()))
	matrix = []
	for i in range(n):
		row = list(map(int, input().split()))
		row.sort()
		matrix.append(row)
	ans = []

	def FindMax():
		maxm = 0
		for i in range(n):
			x = matrix[i][-1]
			if maxm < x:
				maxm = x
		return maxm

	def FindMin():
		minm = 1000000000
		for i in range(n):
			y = matrix[i][0]
			if minm > y:
				minm = y
		return minm
	row = []
	for j in range(m):
		row = []
		minDone = False
		maxDone = False
		minm = FindMin()
		maxm = FindMax()
		for i in range(n):
			if matrix[i][0] == minm and minDone == False:
				row.append(minm)
				matrix[i].pop(0)
				minDone = True
			elif matrix[i][0] == minm and matrix[i][-1] == maxm and (minDone == False):
				row.append(minm)
				matrix[i].pop(0)
				minDone = True
			elif matrix[i][-1] == maxm and maxDone == False:
				row.append(maxm)
				matrix[i].pop()
				maxDone = True
			else:
				row.append(matrix[i][-1])
				matrix[i].pop()
		ans.append(row)
	for i in range(n):
		for j in range(m):
			if j == m - 1:
				print(ans[j][i])
			else:
				print(ans[j][i], end=' ')


def helper(a, m):
	pool = sum(a, [])
	pool.sort()
	tar = pool[:m]
	used = [0] * m
	res = [[0] * m for j in range(len(a))]
	for i in range(len(a)):
		a[i].sort()
		for j in range(m):
			if used[j] == 0 and a[i][0] == tar[j]:
				res[i][j] = a[i].pop(0)
				used[j] = 1
			else:
				res[i][j] = a[i].pop()
	return res
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split(' '))
	b = [[] for j in range(n)]
	for j in range(n):
		b[j] = list(map(int, input().split(' ')))
	res = helper(b, m)
	for j in range(n):
		print(' '.join(map(str, res[j])))


for t in range(int(input())):
	(n, m) = [int(x) for x in input().split()]
	l = []
	for i in range(n):
		l.append(sorted([int(x) for x in input().split()]))
	sol = []
	for j in range(m):
		x = 10 ** 9
		ind = -1
		for i in range(n):
			if x > l[i][0]:
				x = l[i][0]
				ind = i
		sol.append([])
		for i in range(n):
			if i != ind:
				sol[j].append(l[i].pop())
			else:
				sol[j].append(l[i].pop(0))
	for i in range(n):
		for j in range(m):
			print(sol[j][i], end=' ')
		print('')


from sys import stdin
input = stdin.readline
from collections import Counter
tcs = int(input())
for tc in range(tcs):
	(n, m) = list(map(int, input().split()))
	L = []
	first_m = []
	for i in range(n):
		p = list(map(int, input().split()))
		p.sort()
		L.append(p)
		first_m.extend(p)
	first_m.sort()
	di = Counter(first_m[:m])
	top = m
	rft = []
	for i in range(n):
		for j in range(m):
			t = L[i][j]
			if t in di and di[t]:
				top -= 1
				di[t] -= 1
				rft.append([i, j, i, top])
				if top == 0:
					break
		if top == 0:
			break
	for (i, j, k, l) in rft:
		(L[i][j], L[k][l]) = (L[k][l], L[i][j])
	for i in L:
		print(*i)


import sys

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def N():
	return int(inp())

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def testcase(t):
	for p in range(t):
		solve()

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[start:start + _load] for start in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for start in range(len(_fen_tree)):
			if start | start + 1 < len(_fen_tree):
				_fen_tree[start | start + 1] += _fen_tree[start]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		A = 0
		while end:
			A += _fen_tree[end - 1]
			end &= end - 1
		return A

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

def YES():
	print('YES')

def NO():
	print('NO')

def Yes():
	print('Yes')

def No():
	print('No')

def solve():
	(n, m) = sep()
	ar = []
	for _ in range(n):
		ar.append(lis())
	temp = []
	for i in range(n):
		temp.append(SortedList(ar[i]))
	ans = []
	for i in range(m):
		ttt = []
		mi = 9999999999999999
		mindex = -1
		for j in range(n):
			if temp[j][0] < mi:
				mi = temp[j][0]
				mindex = j
		for j in range(n):
			if j == mindex:
				ttt.append(temp[j][0])
				temp[j].remove(temp[j][0])
			else:
				ttt.append(temp[j][-1])
				temp[j].remove(temp[j][-1])
		ans.append(list(ttt))
	for j in range(len(ans[0])):
		cc = []
		for i in range(len(ans)):
			cc.append(ans[i][j])
		print(*cc)
testcase(N())


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	lst = []
	for i in range(n):
		l = list(map(int, input().split(' ')))
		for j in l:
			lst.append([j, i])
	ans = [[0] * m for i in range(n)]
	lst.sort()
	for i in range(m):
		ans[lst[i][1]][i] = lst[i][0]
	temp = [[] for i in range(n)]
	for i in range(m, m * n):
		temp[lst[i][1]].append(lst[i][0])
	for i in range(n):
		for j in range(m):
			if ans[i][j] == 0:
				ans[i][j] = temp[i][-1]
				temp[i].pop()
	for k in ans:
		print(*k)


testtest = int(input())
for case in range(testtest):
	(n, m) = (int(i) for i in input().split())
	fristst = [sorted([int(i) for i in input().split()]) for j in range(n)]
	secondddd = [[] for i in fristst]
	for iii in range(m):
		mn = min(range(n), key=lambda x: fristst[x][0])
		for i in range(len(fristst)):
			if i == mn:
				secondddd[i].append(fristst[i].pop(0))
			else:
				secondddd[i].append(fristst[i].pop())
	for testcases in secondddd:
		for i in testcases:
			print(i, end=' ')
		print()


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def printlst(lst):
	print(' '.join(list(map(str, lst))))
t = inp()
for _ in range(t):
	b = []
	(n, m) = invr()
	for _ in range(n):
		b += [inlt()]
		b[-1].sort(reverse=True)
	path = [[-1 for j in range(n)] for i in range(m)]
	for i in range(m):
		mn = float('inf')
		mni = -1
		for j in range(n):
			if b[j][-1] < mn:
				(mn, mni) = (b[j][-1], j)
		b[mni].pop()
		path[i][mni] = mn
	for i in range(m):
		for j in range(n):
			if path[i][j] == -1:
				path[i][j] = b[j].pop()
	for i in range(n):
		printlst([row[i] for row in path])


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	seq_in = []
	seq_out = []
	ss = []
	for i in range(n):
		s = list(map(int, input().split()))
		seq_in.append(s)
		seq_out.append([0] * len(s))
		ss.extend(s)
	ss.sort()
	for i in range(m):
		p = ss.pop(0)
		for j in range(n):
			if p in seq_in[j]:
				seq_in[j].remove(p)
				seq_out[j][i] = p
				break
	for j in range(n):
		for i in range(m):
			if seq_out[j][i] == 0:
				seq_out[j][i] = seq_in[j].pop()
	for line in seq_out:
		print(' '.join(map(str, line)))


test = int(input())
for case in range(test):
	(n, m) = map(int, input().split())
	l = []
	z = []
	y = []
	for i in range(n):
		y = list(map(int, input().split()))
		z += y
		y.sort()
		l.append(y)
		y = []
	z.sort()
	z = z[0:m]
	x = 0
	a = 0
	q = 0
	while x < m:
		a = 0
		for i in range(n):
			for j in range(m):
				if z[x] == l[a][j]:
					(l[a][x], l[a][j]) = (l[a][j], l[a][x])
					l[a][x] = q
					x += 1
					q -= 1
				if x >= m:
					break
			if x >= m:
				break
			a += 1
	x = 0
	for i in range(n):
		for j in range(m):
			if l[i][j] <= 0:
				f = l[i][j]
				f = abs(f)
				l[i][j] = z[f]
				x += 1
	for i in range(n):
		print(*l[i])


def morning_jogging(data, m, n):
	result = list()
	for _ in range(n):
		result.append(list())
	for _ in range(m):
		min_v = data[0][0]
		min_i = 0
		for i in range(n):
			if data[i][0] < min_v:
				min_v = data[i][0]
				min_i = i
		for i in range(n):
			if i == min_i:
				result[i].append(ds[i].pop(0))
			else:
				result[i].append(ds[i].pop(-1))
	return result
n_test_case = int(input())
test_cases = list()
for _ in range(n_test_case):
	s = input()
	s = s.split(' ')
	n = int(s[0])
	m = int(s[1])
	ds = list()
	for j in range(n):
		s = input()
		s = s.split(' ')
		d = map(int, s)
		ds.append(sorted(d))
	test_cases.append((ds, m, n))
for (ds, m, n) in test_cases:
	res = morning_jogging(ds, m, n)
	for d in res:
		print(' '.join(map(str, d)))


import sys
import heapq

def main(n, m, P):
	ans = [[-1 for j in range(m)] for i in range(n)]
	for p in P:
		heapq.heapify(p)
	P = [[P, i] for (i, P) in enumerate(P)]
	heapq.heapify(P)
	for j in range(m):
		ans[P[0][1]][j] = heapq.heappop(P[0][0])
		heapq.heapify(P)
	P.sort(key=lambda x: x[1])
	for i in range(n):
		for j in range(m):
			if ans[i][j] == -1:
				ans[i][j] = P[i][0].pop()
	return [[str(y) for y in x] for x in ans]
n_test = int(input())
for i in range(n_test):
	(n, m) = [int(x) for x in input().split(' ')]
	P = []
	for j in range(n):
		P.append([int(x) for x in input().split(' ')])
	res = main(n, m, P)
	for tmp in res:
		print(' '.join(tmp))


t = int(input())
for i in range(t):
	line = input()
	line = line.split(' ')
	n = int(line[0])
	m = int(line[1])
	nums = []
	answer = []
	for k in range(n):
		line = input()
		line = line.split(' ')
		answer.append(line)
	index = 0
	for k in range(n):
		for j in range(m):
			nums.append((int(answer[k][j]), k, j))
	nums.sort(key=lambda tup: tup[0])
	best_nums = nums[:m]
	index = 0
	for k in best_nums:
		value = k[0]
		row = k[1]
		if int(value) == int(answer[row][index]):
			index += 1
			continue
		temp = answer[row][index]
		answer[row][index] = value
		for j in range(1, m + 1):
			if int(answer[row][(index + j) % m]) == value:
				answer[row][(index + j) % m] = temp
				break
		index += 1
	for k in range(n):
		out = ''
		for num in answer[k]:
			out += str(num) + ' '
		print(out[:-1])


def get_input(first=False):
	l = [int(e) for e in input().split()]
	if first:
		return l[0]
	return l
for _ in range(get_input(True)):
	(n, m) = get_input()
	S = []
	sol = []
	for i in range(n):
		sol.append([None] * m)
		for bj in get_input():
			S.append((bj, i))
	S.sort()
	for k in range(m):
		(b, i) = S.pop(0)
		sol[i][k] = b
	ind = [0] * n
	while S:
		(b, i) = S.pop()
		while sol[i][ind[i]] is not None:
			ind[i] += 1
		sol[i][ind[i]] = b
		ind[i] += 1
	for b in sol:
		print(*b)


import sys
from collections import defaultdict
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a += (list(map(int, input().split())),)
	arr = []
	for i in range(n):
		for j in range(m):
			arr += ((a[i][j], i, j),)
	arr.sort()
	arr = arr[:m] + sorted(arr[m:], key=lambda x: x[1])
	indList = [None] * n
	for i in range(m, n * m):
		if indList[arr[i][1]] is None:
			indList[arr[i][1]] = i
	ans = [[None] * m for i in range(n)]
	for j in range(m):
		(sw, si, si_plus_1) = arr[j]
		ans[si][j] = sw
		for i in range(n):
			if ans[i][j] is not None:
				continue
			ans[i][j] = arr[indList[i]][0]
			indList[i] += 1
	for a in ans:
		print(*a)


from sys import stdin as sin

def aint():
	return int(input())

def amap():
	return map(int, sin.readline().split())

def alist():
	return list(map(int, sin.readline().split()))

def astr():
	return input()
import heapq as hp
for _ in range(aint()):
	(n, m) = amap()
	b = []
	he = []
	for i in range(n):
		l = alist()
		l.sort()
		b.append(l)
		for j in range(m):
			he.append((l[j], i))
	he.sort(key=lambda x: x[0])
	ans = []
	for i in range(n):
		ans.append([0] * m)
	for i in range(m):
		k = he.pop(0)
		ans[k[1]][i] = k[0]
		for j in range(n):
			if j != k[1]:
				ans[j][i] = b[j].pop(-1)
	for i in ans:
		print(*i)


T = int(input())
for _ in range(T):
	(n, m) = [int(x) for x in input().split()]
	b = []
	for i in range(n):
		b.append([int(x) for x in input().split()])
	a = sorted(b[0][:])
	tired = [(j, a[j], [a[j]]) for j in range(m)]
	tired.sort(key=lambda x: (-x[1], x[0]))
	for i in range(1, n):
		a = sorted(b[i][:])
		tired = [(t[0], min(t[1], a[j]), t[2] + [a[j]]) for (j, t) in enumerate(tired)]
		tired.sort(key=lambda x: (-x[1], x[0]))
	tired.sort()
	result = list(zip(*list(zip(*tired))[2]))
	for row in result:
		print(*row)


import sys
from heapq import heapify, heappop, heappush
from itertools import *
from collections import *
from math import *
sys.setrecursionlimit(10 ** 6)

def power_with_mod(x, y):
	res = 1
	while y:
		if y % 2 == 0:
			x = x * x % mod
			y = y // 2
		else:
			res = res * x % mod
			y -= 1
	return res % mod
TT = int(input())
for y in range(TT):
	(n, m) = map(int, input().split())
	lst = []
	ans = []
	fnl = []
	vis = []
	for i in range(n):
		lst.append(list(map(int, input().split())))
		fnl.append([0] * m)
		vis.append([0] * m)
		for j in range(m):
			ans.append([lst[i][j], i, j])
	ans.sort()
	for i in range(m):
		vis[ans[i][1]][ans[i][2]] = 1
		fnl[ans[i][1]][i] = ans[i][0]
	for i in range(n):
		k = 0
		for j in range(m):
			if vis[i][j] == 0:
				while k < m and fnl[i][k] != 0:
					k += 1
				fnl[i][k] = lst[i][j]
	for i in fnl:
		print(*i)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	rows = []
	for _ in range(n):
		(*row,) = map(int, input().split())
		row.sort()
		rows.append(row)
	ans = [[] for _ in range(n)]
	i = 0
	while i < m:
		mn_row = 0
		for (row_idx, row) in enumerate(rows):
			if rows[mn_row][0] > row[0]:
				mn_row = row_idx
		for (row_idx, row) in enumerate(rows):
			if row_idx == mn_row:
				ans[row_idx].append(row.pop(0))
			else:
				ans[row_idx].append(row.pop())
		i += 1
	for row in ans:
		print(*row)


def inpl():
	return list(map(int, input().split()))

def inpi():
	return int(input())

def sol():
	(n, m) = inpl()
	b = [inpl() for _ in range(n)]
	runners = [[[], 9999999999] for _ in range(m)]
	for i in range(n):
		runners.sort(key=lambda x: x[1])
		b[i].sort(reverse=True)
		for j in range(m):
			runners[j][0].append(b[i][j])
			runners[j][1] = min(runners[j][1], b[i][j])
	for i in range(n):
		print(' '.join((str(runners[j][0][i]) for j in range(m))))
t = int(input())
for _ in range(t):
	sol()


t = int(input())
for t1 in range(t):
	(n, m) = (int(i) for i in input().split())
	paths = [[0 for i in range(m)] for j in range(n)]
	dis = []
	for i in range(n):
		d = [[int(j), i] for j in input().split()]
		dis += d
	dis.sort()
	for i in range(m):
		cp = dis[i][1]
		w = dis[i][0]
		paths[cp][i] = w
	dis1 = sorted(dis[m:], key=lambda x: x[1])
	j = 0
	ind = 0
	while ind < n:
		for i in range(m):
			if paths[ind][i] == 0:
				paths[ind][i] = dis1[j][0]
				j += 1
		ind += 1
	for i in paths:
		print(*tuple(i))


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math
import threading
import sys
import time

def get_int():
	return int(stdin.readline().strip())

def get_tuple():
	return map(int, stdin.readline().split())

def get_list():
	return list(map(int, stdin.readline().split()))

def solve():
	(n, m) = get_tuple()
	arr = []
	for _ in range(n):
		ls = get_list()
		ls.sort()
		arr.append(ls)
	dic = defaultdict(int)
	for i in range(n):
		for j in range(m):
			dic[i, j] = arr[i][j]
	dic = dict(sorted(dic.items(), key=lambda x: x[1]))
	indexes = list(dic.keys())[:m]
	indexes_dic = defaultdict(tuple)
	for val in indexes:
		indexes_dic[val] = val
	col = 0
	for index in indexes:
		(i, j) = indexes_dic[index]
		if (i, col) in indexes_dic:
			indexes_dic[i, col] = (i, j)
		(arr[i][j], arr[i][col]) = (arr[i][col], arr[i][j])
		col += 1
	for i in range(n):
		print(*arr[i])
testcases = True
if testcases:
	t = get_int()
	for _ in range(t):
		solve()
else:
	solve()


def solve():
	(n, m) = map(int, input().split())
	l = []
	ans = []
	temp = []
	for i in range(n):
		l = [int(x) for x in input().split()]
		l.sort(reverse=True)
		ans.append(l)
	for i in range(n):
		for j in range(m):
			temp.append(ans[i][j])
	temp.sort()
	temp = temp[:m]
	k = 0
	for i in range(n):
		ans1 = ans[i]
		for j in range(m):
			if ans1[j] in temp:
				lo = ans1[j]
				(ans1[k], ans1[j]) = (ans1[j], ans1[k])
				temp.remove(lo)
				k += 1
		print(*ans1)
for _ in range(int(input())):
	solve()


from heapq import nsmallest
from sys import stdin, gettrace
if gettrace():

	def inputi():
		return input()
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def solve():
	(n, m) = map(int, input().split())
	bb = [[int(a) for a in input().split()] for _ in range(n)]
	bbl = nsmallest(m, ((i, j) for i in range(n) for j in range(m)), key=lambda x: bb[x[0]][x[1]])
	res = [[-1] * m for _ in range(n)]
	for (r, (i, j)) in enumerate(bbl):
		res[i][r] = bb[i][j]
		bb[i][j] = -1
	bbr = [[] for _ in range(n)]
	for i in range(n):
		bbr = (b for b in bb[i] if b != -1)
		for j in range(m):
			if res[i][j] == -1:
				res[i][j] = next(bbr)
	for r in res:
		print(' '.join(map(str, r)))

def main():
	t = int(input())
	for _ in range(t):
		solve()
main()


from bisect import bisect, bisect_left
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().split())

def RLL():
	return list(map(int, sys.stdin.readline().split()))

def N():
	return int(input())

def A(n):
	return [0] * n

def AI(n, x):
	return [x] * n

def A2(n, m):
	return [[0] * m for i in range(n)]

def G(n):
	return [[] for i in range(n)]

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
mod = 10 ** 9 + 7
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	fact(x, mod)
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa.reverse()

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def floorsum(a, b, c, n):
	if a == 0:
		return b // c * (n + 1)
	if a >= c or b >= c:
		return floorsum(a % c, b % c, c, n) + b // c * (n + 1) + a // c * n * (n + 1) // 2
	m = (a * n + b) // c
	return n * m - floorsum(c, c - b - 1, a, m - 1)

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

def lowbit(n):
	return n & -n

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class ST:

	def __init__(self, arr):
		n = len(arr)
		mx = n.bit_length()
		self.st = [[0] * mx for i in range(n)]
		for i in range(n):
			self.st[i][0] = arr[i]
		for j in range(1, mx):
			for i in range(n - (1 << j) + 1):
				self.st[i][j] = max(self.st[i][j - 1], self.st[i + (1 << j - 1)][j - 1])

	def query(self, l, r):
		if l > r:
			return -inf
		s = (r + 1 - l).bit_length() - 1
		return max(self.st[l][s], self.st[r - (1 << s) + 1][s])

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] > self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return flag

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		seen.add(u)
		for (v, w) in graph[u]:
			if v not in d or d[v] > d[u] + w:
				d[v] = d[u] + w
				heappush(heap, (d[v], v))
	return d

def bell(s, g):
	dis = AI(n, inf)
	dis[s] = 0
	for i in range(n - 1):
		for (u, v, w) in edge:
			if dis[v] > dis[u] + w:
				dis[v] = dis[u] + w
	change = A(n)
	for i in range(n):
		for (u, v, w) in edge:
			if dis[v] > dis[u] + w:
				dis[v] = dis[u] + w
				change[v] = 1
	return dis

def lcm(a, b):
	return a * b // gcd(a, b)

def lis(nums):
	res = []
	for k in nums:
		i = bisect.bisect_left(res, k)
		if i == len(res):
			res.append(k)
		else:
			res[i] = k
	return len(res)

def RP(nums):
	n = len(nums)
	s = set(nums)
	d = {}
	for (i, k) in enumerate(sorted(s), 1):
		d[k] = i
	bi = BIT([0] * (len(s) + 1))
	ans = 0
	for i in range(n - 1, -1, -1):
		ans += bi.query(d[nums[i]] - 1)
		bi.update(d[nums[i]], 1)
	return ans

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None

def nb(i, j, n, m):
	for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:
		if 0 <= ni < n and 0 <= nj < m:
			yield (ni, nj)

def topo(n):
	q = deque()
	res = []
	for i in range(1, n + 1):
		if ind[i] == 0:
			q.append(i)
			res.append(i)
	while q:
		u = q.popleft()
		for v in g[u]:
			ind[v] -= 1
			if ind[v] == 0:
				q.append(v)
				res.append(v)
	return res

@bootstrap
def gdfs(r, p):
	for ch in g[r]:
		if ch != p:
			yield gdfs(ch, r)
	yield None
t = N()
for i in range(t):
	(n, m) = RL()
	b = []
	ans = A2(n, m)
	for i in range(n):
		b.append(RLL())
	pq = []
	for i in range(n):
		for j in range(m):
			heappush(pq, (b[i][j], i, j))
	s = set()
	for i in range(m):
		(v, r, c) = heappop(pq)
		ans[r][i] = v
		s.add(r * m + c)
	for i in range(n):
		cj = 0
		for j in range(m):
			if i * m + j in s:
				continue
			while cj < m and ans[i][cj]:
				cj += 1
			ans[i][cj] = b[i][j]
			cj += 1
	for r in ans:
		print(*r)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd
for t in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(sorted(list(map(int, input().split()))))
	l1 = []
	for i in l:
		l1.extend(i)
	l1.sort()
	d = dd(int)
	for i in range(m):
		d[l1[i]] += 1
	x = 0
	ans = []
	for i in range(n):
		l2 = []
		l3 = []
		for j in range(m):
			if d[l[i][j]]:
				l2.append(l[i][j])
				d[l[i][j]] -= 1
			else:
				l3.append(l[i][j])
		y = len(l2)
		l4 = [0] * m
		for j in range(x, min(m, x + len(l2))):
			l4[j] = l2.pop()
		for j in range(m):
			if not l4[j]:
				if len(l3):
					l4[j] = l3.pop()
				else:
					l4[j] = l2.pop()
		ans.append(l4)
		x = min(x + y, m - 1)
	for i in ans:
		print(*i)


def main():

	class PriorityQueue:

		class Reverse:

			def __init__(self, val):
				self.val = val

			def __lt__(self, other):
				return self.val > other.val

			def __repr__(self):
				return repr(self.val)

		def __init__(self, a=None, desc=False):
			import heapq
			self.heapq = heapq
			self.__container = []
			if a:
				self.__container = a[:]
			if desc:
				for i in range(len(self.__container)):
					self.__container[i] = self.Reverse(self.__container[i])
				self.pop = self.__pop_desc
				self.push = self.__push_desc
				self.top = self.__top_desc
				self.pushpop = self.__pushpop_desc
				self.poppush = self.__poppush_desc
			else:
				self.pop = self.__pop_asc
				self.push = self.__push_asc
				self.top = self.__top_asc
				self.pushpop = self.__pushpop_asc
				self.poppush = self.__poppush_asc
			self.heapq.heapify(self.__container)

		@property
		def is_empty(self):
			return not self.__container

		def __pop_asc(self):
			return self.heapq.heappop(self.__container)

		def __pop_desc(self):
			return self.heapq.heappop(self.__container).val

		def __push_asc(self, item):
			self.heapq.heappush(self.__container, item)

		def __push_desc(self, item):
			self.heapq.heappush(self.__container, self.Reverse(item))

		def __top_asc(self):
			return self.__container[0]

		def __top_desc(self):
			return self.__container[0].val

		def __pushpop_asc(self, item):
			return self.heapq.heappushpop(self.__container, item)

		def __pushpop_desc(self, item):
			return self.heapq.heappushpop(self.__container, self.Reverse(item)).val

		def __poppush_asc(self, item):
			return self.heapq.heapreplace(self.__container, item)

		def __poppush_desc(self, item):
			return self.heapq.heapreplace(self.__container, self.Reverse(item)).val

		def sum(self):
			return sum(self.__container)

		def __len__(self):
			return len(self.__container)

		def __str__(self):
			return str(sorted(self.__container))

		def __repr__(self):
			return self.__str__()
	import sys
	read = sys.stdin.read
	readline = sys.stdin.readline
	INF = 1 << 60
	MOD = 10 ** 9 + 7
	sys.setrecursionlimit(10 ** 5)
	T = int(readline())
	for _ in range(T):
		(N, M) = map(int, readline().split())
		A = [*map(int, readline().split())]
		print(*A)
		B = [(x, i) for (i, x) in enumerate(A)]
		pq = PriorityQueue(B, desc=True)
		for _ in range(N - 1):
			res = [-1] * M
			A = [*map(int, readline().split())]
			A.sort()
			p = 0
			for j in range(M):
				(x, i) = pq.top()
				y = A[j]
				if y < x:
					pq.pop()
					res[i] = y
					pq.push((y, i))
					p = j + 1
				else:
					break
			for j in range(M):
				if res[j] == -1:
					res[j] = A[p]
					p += 1
			print(*res)
main()


import sys
import math

def read_ints():
	inp = input().split()
	inp = [int(x) for x in inp]
	return inp

def read_strings():
	inp = input()
	s = [inp[i] for i in range(len(inp))]
	return s
t = int(input())
for _ in range(t):
	nm = read_ints()
	n = nm[0]
	m = nm[1]
	b = [[] for i in range(n)]
	include_from_patch = [0 for i in range(m)]
	ans = [[0 for j in range(n)] for i in range(m)]
	for i in range(n):
		b[i] = read_ints()
		b[i].sort()
	for i in range(m):
		min = 10 ** 9 + 1
		ind = -1
		for j in range(n):
			if b[j][0] < min:
				ind = j
				min = b[j][0]
		ans[i][ind] = b[ind].pop(0)
		include_from_patch[i] = ind
	for i in range(m):
		for j in range(n):
			if include_from_patch[i] != j:
				val = b[j].pop(0)
				ans[i][j] = val
			else:
				continue
		ans[i] = [str(x) for x in ans[i]]
	for i in range(n):
		tmp = []
		for j in range(m):
			tmp.append(ans[j][i])
		print(' '.join(tmp))


t = int(input())
for z in range(t):
	(n, m) = map(int, input().split())
	ans = []
	fin = []
	kk = []
	for i in range(n):
		arr = list(map(int, input().split()))
		ans.append([0] * m)
		kk.append(arr)
		for j in range(m):
			fin.append([arr[j], j, i])
	fin.sort()
	index = 0
	for i in range(m):
		ans[fin[i][2]][i] = fin[i][0]
	for i in range(m - 1, -1, -1):
		kk[fin[i][2]][fin[i][1]] = 0
	i = 0
	while i < n:
		p = 0
		j = 0
		while j < m:
			if ans[i][j] == 0:
				while kk[i][p] == 0:
					p = p + 1
				ans[i][j] = kk[i][p]
				p = p + 1
			j = j + 1
		i = i + 1
	for ar in ans:
		print(*ar)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = []
	for _ in range(n):
		b = list(map(int, input().split()))
		b.sort()
		a.append(b)
	ans = []
	for i in range(m):
		inside = []
		for j in range(len(a)):
			inside.append(a[j][0])
		mini = min(inside)
		miniIndex = inside.index(mini)
		inside2 = []
		for j in range(len(a)):
			if j != miniIndex:
				inside2.append(a[j][-1])
				a[j].pop(-1)
			else:
				inside2.append(a[j][0])
				a[j].pop(0)
		ans.append(inside2)
	i = 0
	while i < n:
		ans1 = ''
		for j in range(len(ans)):
			ans1 += str(ans[j][i]) + ' '
		print(ans1)
		i += 1


import sys
import math
from collections import defaultdict
from sys import stdin
input = stdin.readline
m = 10 ** 9 + 7
sys.setrecursionlimit(10 ** 5)
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	f = 1
	path = []
	rm = []
	for i in range(n):
		arr = list(map(int, input().split()))
		path.append(arr)
		for j in arr:
			rm.append([j, i])
	ans = [[0] * m for _ in range(n)]
	c = 0
	if True:
		rm.sort()
		while c < m:
			l = rm[c]
			r = l[1]
			val = l[0]
			ans[r][c] = val
			c += 1
	for i in range(n):
		l = []
		ch = path[i]
		s = set(ch)
		ac = set(ans[i])
		for p in s:
			if p != 0:
				c = ch.count(p) - ans[i].count(p)
				for k in range(c):
					l.append(p)
		if len(l):
			k = 0
			for j in range(m):
				if ans[i][j] == 0:
					ans[i][j] = l[k]
					k += 1
		else:
			ans[i] = path[i]
	for i in ans:
		print(*i)


import math
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	b = []
	for _ in range(n):
		a = list(map(int, input().split()))
		b.append(a)
	l = []
	for i in range(n):
		for j in range(m):
			l.append([b[i][j], i, j])
	l.sort()
	c = l[m:]
	s = [[-1] * m for _ in range(n)]
	for i in range(m):
		s[l[i][1]][i] = l[i][0]
	for x in c:
		g = s[x[1]].index(-1)
		s[x[1]][g] = x[0]
	for x in s:
		print(*(i for i in x))


from sys import stdin, stdout
get_string = lambda : stdin.readline().strip('\n')
get_intmap = lambda : map(int, get_string().split(' '))

def testcase():
	(n, m) = get_intmap()
	b = [[sorted(get_intmap()), 0, m - 1] for i in range(n)]
	ans = [[0] * n for i in range(m)]
	for runner in range(m):
		(min_so_far, min_node, max_so_far) = (10000000000.0, -1, -1)
		for node in range(n):
			(l, x, y) = b[node]
			(vx, vy) = (l[x], l[y])
			if vx < min_so_far:
				(min_so_far, min_node) = (vx, node)
		for node in range(n):
			if node == min_node:
				ans[runner][node] = b[node][0][b[node][1]]
				b[node][1] += 1
			else:
				ans[runner][node] = b[node][0][b[node][2]]
				b[node][2] -= 1
	for node in range(n):
		print(' '.join([str(ans[runner][node]) for runner in range(m)]))
for t in range(int(input())):
	testcase()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		a = list(map(int, input().split()))
		a.sort(reverse=True)
		l.append(a)
	for i in range(m - 1):
		ind = -1
		minn = 1000000000
		for j in range(n):
			if l[j][-1] < minn:
				minn = l[j][-1]
				ind = j
		ele = l[ind].pop()
		l[ind].insert(i, ele)
	for i in l:
		print(' '.join(map(str, i)))


def some_random_function():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function5():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)
import os, sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		a = [list(map(int, input().split())) for _ in range(n)]
		x = []
		for i in range(n):
			for j in range(m):
				x.append((a[i][j], i, j))
		x.sort(key=lambda xx: xx[0])
		le = set()
		ans = [[0] * m for _ in range(n)]
		for i in range(m):
			le.add((x[i][1], x[i][2]))
			ans[x[i][1]][i] = x[i][0]
		for i in range(n):
			k = 0
			for j in range(m):
				if (i, j) not in le:
					while k != m and ans[i][k]:
						k += 1
					if k != m:
						ans[i][k] = a[i][j]
						k += 1
		for i in ans:
			print(*i)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def some_random_function1():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function2():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function3():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function4():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function6():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function7():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)

def some_random_function8():
	x = 10
	x *= 100
	i_dont_know = x
	why_am_i_writing_this = x * x
	print(i_dont_know)
	print(why_am_i_writing_this)
main()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = []
	s1 = [[0 for i in range(m)] for j in range(n)]
	max_num = 10000000001
	y = 0
	ans = 0
	for i in range(n):
		a = [int(i) for i in input().split()]
		a.sort()
		s.append(a)
	for i in range(m):
		x = s[0][0]
		y = 0
		for j in range(1, n):
			if s[j][0] < x:
				s1[y][i] = s[y][-1]
				s[y].pop(-1)
				x = s[j][0]
				y = j
			else:
				s1[j][i] = s[j][-1]
				s[j].pop(m - i - 1)
		s1[y][i] = x
		s[y].pop(0)
	for i in range(n):
		for j in range(m):
			print(s1[i][j], end=' ')
		print()


cases = int(input())
for case in range(0, cases):
	first_input = [int(x) for x in input().split(' ')]
	n = first_input[0]
	m = first_input[1]
	b = []
	flat_b = []
	for i in range(0, n):
		b.append([int(x) for x in input().split(' ')])
		for x in b[i]:
			flat_b.append(x)
	flat_b = sorted(flat_b)
	flat_b = flat_b[0:m]
	not_finished = [i for i in range(0, m)]
	finished = []
	for i in range(0, n):
		row_finished = []
		for j in range(0, m):
			num = b[i][j]
			if j in row_finished:
				continue
			if i == 0:
				if b[i][j] in flat_b:
					not_finished.remove(j)
					flat_b.remove(num)
			else:
				if b[i][j] in flat_b and j not in not_finished:
					for k in range(0, m):
						if k == j or b[i][k] in flat_b or k not in not_finished:
							continue
						(b[i][j], b[i][k]) = (b[i][k], b[i][j])
						not_finished.remove(k)
						flat_b.remove(num)
						row_finished.append(k)
						break
				if b[i][j] in flat_b and j in not_finished:
					not_finished.remove(j)
					flat_b.remove(num)
			if len(not_finished) == 0:
				break
		if len(not_finished) == 0:
			break
	for row in b:
		print(*row)


def solve():
	(n, m) = (int(x) for x in input().split())
	b = [sorted([int(x) for x in input().split()]) for _ in range(n)]
	ans = [[] for _ in range(n)]
	for i in range(m):
		mn = min(range(n), key=lambda x: b[x][0])
		for j in range(len(b)):
			if j == mn:
				ans[j].append(b[j].pop(0))
			else:
				ans[j].append(b[j].pop())
	for row in ans:
		for col in row:
			print(col, end=' ')
		print()
for _ in range(int(input())):
	solve()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import ceil

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	(n, m) = map(int, input().split())
	a = []
	els = []
	for i in range(n):
		a += [list(map(int, input().split()))]
		for j in range(m):
			els += [(a[i][j], i, j)]
	els = sorted(els, key=lambda x: x[0])
	assign = [[-1] * m for i in range(n)]
	for i in range(m):
		(el, p, q) = els[i]
		assign[p][q] = i
	for i in range(n):
		st = set(assign[i])
		pp = []
		for j in range(m):
			if j not in st:
				pp += [j]
		for j in range(m):
			if assign[i][j] == -1:
				assign[i][j] = pp.pop()
	ans = [[] for i in range(m)]
	for i in range(n):
		b = []
		for j in range(m):
			b += [(assign[i][j], a[i][j])]
		b = sorted(b, key=lambda x: x[0])
		print(*[k[1] for k in b])


from importlib import import_module
import math
MOD = 10 ** 9 + 7
phi = (1 + pow(5, 1 / 2)) / 2
phi_hat = (1 - pow(5, 1 / 2)) / 2
ln = len

class CodeJam:

	def __init__(self):
		self.np = import_module('numpy')
		self.sp = import_module('scipy')

class Tool:

	def __init__(self):
		self.functools = import_module('functools')
		self.itertools = import_module('itertools')
		self.operator = import_module('operator')
		self.collections = import_module('collections')

	def count_to_dict(self, arr):
		counter = self.collections.Counter(arr)
		return dict(counter.most_common())

class Sort:

	def __init__(self):
		self.heapq = import_module('heapq')

class Input:

	def __init__(self):
		self.inp = input

	@property
	def s(self):
		return self.inp()

	@property
	def i(self):
		return int(self.s)

	@property
	def arr(self):
		return self.inp().split(' ')

	@property
	def iarr(self):
		return list(map(int, self.arr))
F = lambda i: int((pow(phi, i) - pow(phi_hat, i)) / pow(5, 1 / 2))
L = lambda i: int(pow(phi, i) + pow(phi_hat, i))

def prime_factors(n):
	factors = []
	i = 2
	while i * i <= n:
		while n % i == 0:
			n = n // i
			factors.append(i)
		i += 1
	return factors + [n] * (n != 1)

def fprint(*args, **kwargs):
	print(*args, **kwargs, flush=True)
pass

def solve(inp, t):
	(n, m) = inp.iarr
	b = [sorted(inp.iarr) for _ in range(n)]
	res = [[] for _ in range(n)]
	for i in range(m):
		c = 0
		v = float('inf')
		for j in range(n):
			if b[j][0] < v:
				c = j
				v = b[j][0]
		res[c].append(b[c].pop(0))
		for k in range(n):
			if k != c:
				res[k].append(b[k].pop())
	for i in range(n):
		print(*res[i])

def main():
	inp = Input()
	for t in range(inp.i):
		solve(inp, t)
main()


import sys, math, itertools, random, bisect
from collections import defaultdict
INF = 10 ** 18

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def input():
	return sys.stdin.readline().strip()
mod = 10 ** 9 + 7
test = 1
test = int(input())
for _ in range(test):
	(n, m) = get_ints()
	a = []
	b = []
	for i in range(n):
		x = get_array()
		a.append(sorted(x))
		for ele in x:
			b.append([ele, i])
	b.sort()
	b = b[:m]
	b.sort(key=lambda x: x[1])
	p = 0
	for i in range(n):
		ct = 0
		ind = p
		while p < m and b[p][1] == i:
			ct += 1
			p += 1
		k = 0
		l = m - 1
		for j in range(m):
			if ind <= j < ind + ct:
				print(a[i][k], end=' ')
				k += 1
			else:
				print(a[i][l], end=' ')
				l -= 1
		print()


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	a = []
	b = []
	for i in range(n):
		temp = list(map(int, input().split()))
		for j in range(0, len(temp)):
			a.append((temp[j], (i, j)))
		b.append(temp)
	a.sort(key=lambda x: x[0])
	done = set()
	mini = set()
	for i in range(m):
		mini.add(a[i][1])
	ans = [[0 for _ in range(m)] for _ in range(n)]
	for i in range(0, m):
		(x, y) = a[i][1]
		ans[x][y] = i
		for j in range(0, n):
			if j == x:
				continue
			for k in range(0, m):
				if (j, k) in done or (j, k) in mini:
					continue
				ans[j][k] = i
				done.add((j, k))
				break
	final = [[0 for _ in range(m)] for _ in range(n)]
	for i in range(n):
		for j in range(m):
			final[i][ans[i][j]] = b[i][j]
	for i in final:
		print(*i)


import bisect
t = int(input())

def solution(arr, n, m):
	result = []
	min_indexes = []
	for i in range(n):
		arr[i].sort()
		bisect.insort(min_indexes, [arr[i][0], i])
		result.append([])
	while len(arr[0]) != 0:
		min_i = min_indexes[0][1]
		for i in range(n):
			if i == min_i:
				result[i].append(arr[i][0])
				arr[i] = arr[i][1:]
			else:
				result[i].append(arr[i][-1])
				arr[i] = arr[i][:-1]
		min_indexes = min_indexes[1:]
		if len(arr[0]) != 0:
			bisect.insort(min_indexes, [arr[min_i][0], min_i])
	return result
for _ in range(t):
	(n, m) = [int(i) for i in input().split(' ')]
	arr = []
	for i in range(n):
		arr.append([int(a) for a in input().split(' ')])
	res = solution(arr, n, m)
	for line in res:
		print(' '.join([str(i) for i in line]))


import sys
import math
t = int(sys.stdin.readline())
for _ in range(t):
	(n, m) = [int(i) for i in sys.stdin.readline().split()]
	paths = [[]] * n
	paths2 = [[]] * n
	for i in range(n):
		paths[i] = [int(i) for i in sys.stdin.readline().split()]
		paths2[i] = [0] * m
		for j in range(m):
			paths2[i][j] = paths[i][j]
	ans = [[]] * m
	for runner in range(m):
		choice = [0] * n
		global_min = 10 ** 9
		loc = (-1, -1)
		for i in range(n):
			for j in range(m):
				if paths[i][j] != -1 and paths[i][j] < global_min:
					global_min = paths[i][j]
					loc = (i, j)
		choice[loc[0]] = loc[1]
		paths[loc[0]][loc[1]] = -1
		for i in range(n):
			if i == loc[0]:
				continue
			ma = -1
			l = -1
			for j in range(m):
				if paths[i][j] > ma:
					ma = paths[i][j]
					l = j
			choice[i] = l
			paths[i][l] = -1
		ans[runner] = choice
	for i in range(n):
		line = ['0'] * m
		for j in range(m):
			line[j] = str(paths2[i][ans[j][i]])
		print(' '.join(line))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	lst = []
	b = []
	for i in range(n):
		temp = list(map(int, input().split()))
		for ele in temp:
			lst.append([i, ele])
		b.append(temp)
	lst.sort(key=lambda x: x[1])
	ans = [[0 for j in range(n)] for i in range(m)]
	for i in range(m):
		ans[i][lst[i][0]] = lst[i][1]
		lst[i][1] = -1
	lst.sort(key=lambda x: x[0])
	possible = [[-1 for j in range(m)] for i in range(n)]
	i = 0
	while i < len(lst):
		for j in range(m):
			possible[lst[i][0]][j] = lst[i][1]
			i += 1
	for i in range(n):
		for j in range(m):
			if ans[j][i] == 0:
				for k in range(m):
					if possible[i][k] != -1:
						ans[j][i] = possible[i][k]
						possible[i][k] = -1
						break
	for i in range(n):
		for j in range(m):
			print(ans[j][i], end=' ')
		print()


def getInput():
	return sys.stdin.readline().strip()

def getInt():
	return int(getInput())

def getInts():
	return map(int, getInput().split())

def getArray():
	return list(getInts())
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	li = []
	flaglist = []
	for i in range(n):
		lis = list(map(int, input().split()))
		li.append(lis)
		flag = [0] * m
		flaglist.append(flag)
	minlist = []
	for i in range(n):
		for j in li[i]:
			minlist.append(j)
	minlist.sort()
	minlist = minlist[:m]
	for k in range(len(minlist)):
		k1 = False
		for i in range(n):
			for j in range(m):
				if li[i][j] == minlist[k] and flaglist[i][j] == 0:
					(li[i][j], li[i][k]) = (li[i][k], li[i][j])
					flaglist[i][k] = 1
					k1 = True
					break
			if k1 == True:
				break
	for i in li:
		print(*i)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
t = inp()
for case in range(0, t):
	nm = inlt()
	n = nm[0]
	m = nm[1]
	all = []
	ls = []
	lans = []
	for i in range(0, n):
		l = inlt()
		ls.append(l)
		all.extend(l)
		lans.append([])
	all.sort()
	p = []
	for i in range(0, m):
		looking = True
		for k in range(0, n):
			if min(ls[k]) == all[i] and looking:
				lans[k].append(all[i])
				ls[k].remove(all[i])
				looking = False
			else:
				lans[k].append(max(ls[k]))
				ls[k].remove(max(ls[k]))
	for i in range(0, n):
		print(' '.join(map(str, lans[i])))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ans = []
	ls = []
	for i in range(n):
		arr = list(map(int, input().split()))
		ls.extend(arr)
		ans.append(arr)
	ls.sort()
	ls = ls[:m]
	f = 0
	vis = [[0 for i in range(m + 1)] for j in range(n + 1)]
	for i in range(m):
		f = 0
		for j in range(n):
			for k in range(m):
				if ans[j][k] == ls[i] and vis[j][k] == 0 and (vis[j][i] == 0):
					f = 1
					(ans[j][k], ans[j][i]) = (ans[j][i], ans[j][k])
					vis[j][i] = 1
					break
			if f == 1:
				break
	for i in ans:
		print(*i)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	array = []
	li = []
	output = [[-1 for _ in range(m)] for _ in range(n)]
	for i in range(n):
		array.append(list(map(int, input().split())))
	sett = set()
	for i in range(n):
		for ii in range(m):
			li.append([array[i][ii], i, ii])
	li.sort()
	for i in range(m):
		output[li[i][1]][i] = li[i][0]
		sett.add((li[i][1], li[i][2]))
	for i in range(n):
		iii = 0
		for ii in range(m):
			while (i, iii) in sett:
				iii += 1
			if output[i][ii] == -1:
				output[i][ii] = array[i][iii]
				iii += 1
	for i in range(n):
		print(*output[i])


def fun(ls, n, m):
	ans = ls
	show = [[] for _ in range(n)]
	count = m
	while count > 0:
		mn = 10 ** 10
		mn_index = -1
		for i in range(n):
			for j in range(count):
				if mn > ans[i][j]:
					mn = ans[i][j]
					mn_index = [i, j]
		for i in range(n):
			if i != mn_index[0]:
				mx = -1
				mx_index = -1
				for j in range(count):
					if mx < ans[i][j]:
						mx = ans[i][j]
						mx_index = [i, j]
				ans[i].pop(mx_index[1])
				show[i].append(mx)
			else:
				ans[mn_index[0]].pop(mn_index[1])
				show[mn_index[0]].append(mn)
		count -= 1
	for i in show:
		print(*i)
T = int(input())
for i in range(T):
	(n, m) = list(map(int, input().split()))
	ls = []
	for i in range(n):
		ks = list(map(int, input().split()))
		ls.append(ks)
	fun(ls, n, m)


def solve(B, n, m):
	AugB = []
	for i in range(n):
		for j in range(m):
			AugB.append((B[i][j], i, j))
	AugB = sorted(AugB)
	mShortestPaths = AugB[:m]
	result = [[0] * m for i in range(n)]
	takenLengthIndices = [set() for i in range(n)]
	for k in range(m):
		(l, i, j) = mShortestPaths[k]
		takenLengthIndices[i].add(j)
		result[i][k] = l
	for i in range(n):
		index = 0
		for k in range(m):
			if result[i][k] == 0:
				while index in takenLengthIndices[i]:
					index += 1
				result[i][k] = B[i][index]
				index += 1
	return result
t = int(input())
for tc in range(t):
	(n, m) = map(int, input().split())
	B = []
	for i in range(n):
		B.append(list(map(int, input().split())))
	result = solve(B, n, m)
	for resultLine in result:
		print(*resultLine)


import os
import sys
from io import BytesIO, IOBase
import math
from collections import Counter
import itertools

def func(n, m, array):
	all_paths = list(itertools.chain.from_iterable(array))
	sorted_path = sorted(range(len(all_paths)), key=lambda k: all_paths[k])
	choosing = {}
	choosing_list = []
	indices = [0] * n
	for val in sorted_path[:m]:
		path = val // m
		pos = val % m
		choosing_list.append((path, pos))
		if path in choosing:
			choosing[path].add(pos)
		else:
			choosing[path] = set([pos])
	shorted_paths = []
	for i in range(m):
		curr = [None] * n
		(path, pos) = choosing_list[i]
		curr[path] = array[path][pos]
		for j in range(n):
			if curr[j] is None:
				while j in choosing and indices[j] in choosing[j]:
					indices[j] += 1
				curr[j] = array[j][indices[j]]
				indices[j] += 1
		shorted_paths.append(curr)
	shorted_paths = list(map(list, zip(*shorted_paths)))
	for path in shorted_paths:
		print(' '.join((str(i) for i in path)))

def main():
	num_test = int(parse_input())
	result = []
	for _ in range(num_test):
		(n, m) = [int(i) for i in parse_input().split()]
		array = []
		for i in range(n):
			array.append([int(i) for i in parse_input().split()])
		func(n, m, array)
parse_input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = []
	mat = []
	for i in range(n):
		temp = list(map(int, input().split()))
		arr += list(zip(temp, [i] * m))
		mat.append(temp)
	arr.sort()
	tempArr = arr[:m]
	newArr = [[] for i in range(n)]
	for i in range(m):
		newArr[tempArr[i][1]].append(tempArr[i][0])
	mark = 0
	for i in range(n):
		row = sorted(mat[i])
		l = len(newArr[i])
		result = row[-mark:] + row[:-mark]
		print(*result)
		mark += l


import sys, os
from difflib import SequenceMatcher
from collections import Counter
from bisect import bisect_left as bl, bisect_right as br
from io import BytesIO, IOBase
from itertools import accumulate
import math
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def memodict(f):

	class memodict(dict):

		def __missing__(self, key):
			ret = self[key] = f(key)
			return ret
	return memodict().__getitem__

def memoize(f):

	class memodict(dict):

		def __getitem__(self, *key):
			return dict.__getitem__(self, key)

		def __missing__(self, key):
			ret = self[key] = f(*key)
			return ret
	return memodict().__getitem__
LCSubstr = lambda a, b: SequenceMatcher(None, a, b).find_longest_match(0, len(a), 0, len(b))

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def pollard_rho(n):
	if n & 1 == 0:
		return 2
	if n % 3 == 0:
		return 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			prev = p
			p = p * p % n
			if p == 1:
				return gcd(prev - 1, n)
			if p == n - 1:
				break
		else:
			for i in range(2, n):
				(x, y) = (i, (i * i + 1) % n)
				f = gcd(abs(x - y), n)
				while f == 1:
					(x, y) = ((x * x + 1) % n, (y * y + 1) % n)
					y = (y * y + 1) % n
					f = gcd(abs(x - y), n)
				if f != n:
					return f
	return n

@memodict
def prime_factors(n):
	if n <= 1:
		return Counter()
	f = pollard_rho(n)
	return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)

def distinct_factors(n):
	factors = [1]
	for (p, exp) in prime_factors(n).items():
		factors += [p ** i * factor for factor in factors for i in range(1, exp + 1)]
	return factors

def all_factors(n):
	(small, large) = ([], [])
	for i in range(1, int(n ** 0.5) + 1, 2 if n & 1 else 1):
		if not n % i:
			small.append(i)
			large.append(n // i)
	if small[-1] == large[-1]:
		large.pop()
	large.reverse()
	small.extend(large)
	return small

def is_prime(n):
	if n < 5 or n & 1 == 0 or n % 3 == 0:
		return 2 <= n <= 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			p = p * p % n
			if p == n - 1:
				break
		else:
			return False
	return True

def prime_sieve(n):
	flag = n % 6 == 2
	sieve = bytearray((n // 3 + flag >> 3) + 1)
	for i in range(1, int(n ** 0.5) // 3 + 1):
		if not sieve[i >> 3] >> (i & 7) & 1:
			k = 3 * i + 1 | 1
			for j in range(k * k // 3, n // 3 + flag, 2 * k):
				sieve[j >> 3] |= 1 << (j & 7)
			for j in range(k * (k - 2 * (i & 1) + 4) // 3, n // 3 + flag, 2 * k):
				sieve[j >> 3] |= 1 << (j & 7)
	return sieve

def prime_list(n):
	res = []
	if n > 1:
		res.append(2)
	if n > 2:
		res.append(3)
	if n > 4:
		sieve = prime_sieve(n + 1)
		res.extend((3 * i + 1 | 1 for i in range(1, (n + 1) // 3 + (n % 6 == 1)) if not sieve[i >> 3] >> (i & 7) & 1))
	return res

def extended_gcd(a, b):
	(s, old_s) = (0, 1)
	(r, old_r) = (b, a)
	while r:
		q = old_r // r
		(old_r, r) = (r, old_r - q * r)
		(old_s, s) = (s, old_s - q * s)
	return (old_r, old_s, (old_r - old_s * a) // b if b else 0)

def modinv(a, m):
	(g, x, _) = extended_gcd(a % m, m)
	return x % m if g == 1 else None

def make_nCr_mod(max_n=2 * 10 ** 5, mod=10 ** 9 + 7):
	max_n = min(max_n, mod - 1)
	(fact, inv_fact) = ([0] * (max_n + 1), [0] * (max_n + 1))
	fact[0] = 1
	for i in range(max_n):
		fact[i + 1] = fact[i] * (i + 1) % mod
	inv_fact[-1] = pow(fact[-1], mod - 2, mod)
	for i in reversed(range(max_n)):
		inv_fact[i] = inv_fact[i + 1] * (i + 1) % mod

	def nCr_mod(n, r):
		res = 1
		while n or r:
			(a, b) = (n % mod, r % mod)
			if a < b:
				return 0
			res = res * fact[a] % mod * inv_fact[b] % mod * inv_fact[a - b] % mod
			n //= mod
			r //= mod
		return res
	return nCr_mod

def binarySearch(arr, l, r, x):
	while l <= r:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
			r = mid - 1
	return -1

def PrefixSum(arr):
	return list(accumulate(arr))

class inputs:

	def single(self):
		return int(input())

	def mul(self):
		return map(int, input().split())

	def list(self):
		return list(map(int, input().split()))
inp = inputs()

def main():
	for _ in range(inp.single()):
		(n, m) = inp.mul()
		a = []
		for i in range(n):
			a.append(inp.list())
		b = [pow(10, 10)] * m
		for i in range(n):
			a[i] = sorted(a[i])
			c = [0] * m
			temp = a[i].copy()
			for j in range(m):
				mx = max(b)
				if a[i][j] >= mx:
					continue
				else:
					for k in range(len(b)):
						if a[i][j] < b[k] and b[k] == mx:
							b[k] = a[i][j]
							c[k] = b[k]
							temp[j] = 0
							break
			for j in temp:
				if j != 0:
					for k in range(m):
						if c[k] == 0:
							c[k] = j
							break
			a[i] = c.copy()
		for i in a:
			print(*i)
main()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	grid = []
	for _ in range(n):
		b = [int(i) for i in input().split()]
		grid.append(b)
	flat = []
	for (i, row) in enumerate(grid):
		for num in row:
			flat.append((num, i))
	flat.sort()
	ans = [[-1] * m for i in range(n)]
	for j in range(m):
		(num, i) = flat[j]
		ans[i][j] = num
	pos = [0] * n
	for (num, i) in flat[m:]:
		while ans[i][pos[i]] != -1:
			pos[i] += 1
		ans[i][pos[i]] = num
		pos[i] += 1
	for row in ans:
		print(*row)


def main():
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		board = []
		all_runs = []
		for i in range(n):
			b = list(map(int, input().split()))
			board.append(b)
			for j in range(m):
				all_runs.append((i, j, b[j]))
		all_runs.sort(key=lambda x: x[2])
		d = {}
		for i in range(m):
			if all_runs[i][0] not in d:
				d[all_runs[i][0]] = 1
			else:
				d[all_runs[i][0]] += 1
		z = 0
		for i in range(n):
			row = [0] * m
			board[i].sort()
			for j in range(m):
				row[(j + z) % m] = board[i][j]
			z += d[i] if i in d else 0
			print(*row)
main()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	g = []
	for i in range(n):
		v = list(map(int, input().split()))
		g.append(v)
		a.append(sorted(v))
	path = []
	for p in range(m):
		mi = 10000000000000000
		h = -1
		for i in range(len(a)):
			mi = min(min(a[i]), mi)
			if mi == min(a[i]):
				h = i
		u = []
		for i in range(len(a)):
			if i != h:
				u.append(a[i][-1])
				a[i].pop(len(a[i]) - 1)
			else:
				u.append(a[h][0])
				a[h].pop(0)
		path.append(u)
	for i in range(len(path[0])):
		for j in range(len(path)):
			print(path[j][i], end=' ')
		print()


class Path:

	def __init__(self, checkpoint, length):
		self.c = checkpoint
		self.l = length

class PathList:

	def __init__(self, l):
		self.l = l

	def pop(self):
		return self.l.pop()
t = int(input())
r = []
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	b = []
	paths = []
	for i in range(n):
		checkpointPaths = list(map(int, input().split()))
		checkpointPaths.sort()
		b.append(PathList(checkpointPaths))
		paths.extend([Path(i, j) for j in checkpointPaths])
	paths.sort(key=lambda x: (x.l, x.c))
	result = [[] for _ in range(n)]
	for i in range(m):
		smallestPath = paths[i]
		result[smallestPath.c].append(smallestPath.l)
		for j in range(n):
			if len(result[j]) < i + 1:
				result[j].append(b[j].pop())
	resStr = '\n'.join([' '.join([str(i) for i in x]) for x in result])
	r.append(resStr)
print('\n'.join(r))


from sys import stdin, stdout
input = stdin.readline
I = int
R = range
listInput = lambda : list(map(int, input().strip().split()))
lineInput = lambda : map(int, input().strip().split())

def main():
	for _ in R(I(input())):
		(n, m) = lineInput()
		ans = [[-1] * m for i in range(n)]
		pathAndRow = []
		for i in range(n):
			for j in listInput():
				pathAndRow.append((j, i))
		pathAndRow.sort()
		for i in range(m):
			ele = pathAndRow.pop(0)
			ans[ele[1]][i] = ele[0]
		while pathAndRow:
			ele = pathAndRow.pop(0)
			itr = 0
			while ans[ele[1]][itr] != -1:
				itr += 1
			ans[ele[1]][itr] = ele[0]
		for i in range(n):
			print(*ans[i])
main()


def solve():
	(r, m) = map(int, input().split(' '))
	paths = []
	for _ in range(r):
		path = list(map(int, input().split(' ')))
		path = sorted(path)
		paths.append(path)
	out = [[] for x in range(r)]
	for x in range(m):
		mins = [10 ** 9 + 1, -1]
		for (i, x) in enumerate(paths):
			if x[0] < mins[0]:
				mins = [x[0], i]
		for (i, x) in enumerate(paths):
			if not i == mins[1]:
				out[i].append(paths[i].pop())
			else:
				out[i].append(paths[mins[1]].pop(0))
	for p in out:
		print(' '.join((str(x) for x in p)))
cases = int(input())
for case in range(cases):
	solve()


import sys
import math
import bisect
import functools
from functools import lru_cache
from sys import stdin, stdout
from math import gcd, floor, sqrt, log, ceil
from heapq import heappush, heappop, heapify
from collections import defaultdict as dd
from collections import Counter as cc
from bisect import bisect_left as bl
from bisect import bisect_right as br

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)
sys.setrecursionlimit(100000000)
intinp = lambda : int(input().strip())
stripinp = lambda : input().strip()
fltarr = lambda : list(map(float, input().strip().split()))
intarr = lambda : list(map(int, input().strip().split()))
ceildiv = lambda x, d: x // d if x % d == 0 else x // d + 1
MOD = 1000000007
num_cases = intinp()
for _ in range(num_cases):
	(n, m) = intarr()
	arr = []
	h = [[0, -math.inf, []] for _ in range(m)]
	for _ in range(n):
		for v in sorted(intarr()):
			(ind, val, path) = heappop(h)
			heappush(h, [ind + 1, -min(-val, v), path + [v]])
	for j in range(n):
		for i in range(m):
			print(h[i][2][j], end=' ')
		print()


t = int(input())
for test in range(t):
	(n, m) = map(int, input().split())
	ans = []
	a = []
	kk = []
	for i in range(n):
		arr = list(map(int, input().split()))
		ans.append([0] * m)
		kk.append(arr)
		for j in range(m):
			a.append([arr[j], j, i])
	a.sort()
	for i in range(m):
		ans[a[i][2]][i] = a[i][0]
	for i in range(m - 1, -1, -1):
		kk[a[i][2]][a[i][1]] = 0
	i = 0
	while i < n:
		p = j = 0
		while j < m:
			if ans[i][j] == 0:
				while kk[i][p] == 0:
					p = p + 1
				ans[i][j] = kk[i][p]
				p = p + 1
			j = j + 1
		i = i + 1
	for ele in ans:
		print(*ele)


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	l = [list(map(int, input().split())) for i in range(n)]
	par = []
	for i in range(n):
		for j in range(m):
			par.append([l[i][j], i, j, 0])
	par.sort()
	ans = [[0] * m for i in range(n)]
	j = 0
	for i in range(n * m):
		ans[par[i][1]][j] = par[i][0]
		par[i][-1] = 1
		j += 1
		if j == m:
			break
	dp = [0] * n
	for i in range(j, n * m):
		if par[i][-1] == 0:
			val = par[i][0]
			row = par[i][1]
			col = dp[par[i][1]]
			while True:
				if ans[row][col] != 0:
					col += 1
				else:
					ans[row][col] = val
					par[i][-1] = 1
					break
	for i in ans:
		print(*i)


def mergemin(li, ln, k):
	a = []
	m = 0
	n = 0
	c = len(ln)
	for i in range(c):
		if li[m][0] > ln[n]:
			a.append((ln[n], k, n))
			n += 1
		else:
			a.append(li[m])
			m += 1
	return a

def convert1st(l):
	l = [(l[i], 0, i) for i in range(len(l))]
	return l

def foo(x):
	x = x.split()
	for (i, v) in enumerate(x):
		x[i] = int(v)
	return x
ix = int(input())
list = []
for a in range(ix):
	l = []
	i1 = input()
	for a in range(foo(i1)[0]):
		r1 = input()
		l.append(sorted(foo(r1)))
		if a == 0:
			ans = convert1st(sorted(foo(r1)))
		else:
			ans = mergemin(ans, sorted(foo(r1)), a)
	k = 0
	for j in ans:
		if j[2] != k:
			(l[j[1]][j[2]], l[j[1]][k]) = (l[j[1]][k], l[j[1]][j[2]])
			try:
				c = ans.index((l[j[1]][j[2]], j[1], k))
				ans[c] = (l[j[1]][j[2]], j[1], j[2])
			except:
				None
		k += 1
	list = list + l
for a in list:
	print(*a)


import sys
import os.path
from collections import *
import math
import bisect
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
t = int(input())
while t:
	t -= 1
	(n, m) = [int(x) for x in input().split()]
	arr = [[0 for i in range(m)] for i in range(n)]
	for i in range(n):
		arr[i] = [int(x) for x in input().split()]
		arr[i].sort()
		arr[i] = deque(arr[i])
	brr = [[0 for i in range(m)] for i in range(n)]
	for j in range(m):
		index = 0
		val = arr[0][0]
		for i in range(n):
			if val > arr[i][0]:
				index = i
				val = arr[i][0]
		for i in range(n):
			if i == index:
				brr[i][j] = arr[i][0]
				arr[i].popleft()
			else:
				brr[i][j] = arr[i][-1]
				arr[i].pop()
	for i in brr:
		for j in i:
			print(j, end=' ')
		print()


from sys import stdin
input = stdin.buffer.readline
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		arr.append([int(x) for x in input().split()])
	dp = [[-1 for i in range(m)] for j in range(n)]
	l = []
	for i in range(n):
		for j in range(m):
			l.append((arr[i][j], i, j))
	l.sort()
	for i in range(m):
		dp[l[i][1]][l[i][2]] = i
	for i in range(n):
		vis = [-1] * m
		for j in range(m):
			if dp[i][j] != -1:
				vis[dp[i][j]] = 1
		j = 0
		k = 0
		while j < m and k < m:
			if dp[i][j] == -1 and vis[k] == -1:
				dp[i][j] = k
				j = j + 1
				k = k + 1
			elif dp[i][j] == -1 and vis[k] == 1:
				k = k + 1
			elif dp[i][j] != -1 and vis[k] == -1:
				j = j + 1
			else:
				j = j + 1
				k = k + 1
	for i in range(n):
		ans = [-1] * m
		for j in range(m):
			ans[dp[i][j]] = arr[i][j]
		print(*ans)


T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	paths = []
	for _ in range(N):
		paths.append(list(map(int, input().split())))
	rem = {}
	for (i, c) in enumerate(paths):
		for (j, time) in enumerate(c):
			if time in rem:
				rem[time].add((i, j))
			else:
				rem[time] = {(i, j)}
	rem = list(rem.items())
	rem.sort(key=lambda elt: elt[0])
	ans = [[-1] * M for _ in range(N)]
	i = 0
	for (time, paths) in rem:
		for path in paths:
			(checkpoint, nb) = path
			if i < M:
				ans[checkpoint][i] = time
				i += 1
			else:
				for j in range(M):
					if ans[checkpoint][j] == -1:
						ans[checkpoint][j] = time
						break
	for elt in ans:
		print(' '.join(map(str, elt)))


import os
import sys
from io import BytesIO, IOBase
import threading
from bisect import bisect_right
from math import gcd, log
from collections import Counter, defaultdict, deque
from pprint import pprint
from itertools import permutations
from bisect import bisect_right
from random import randint as rti

def main(tnum):
	(n, m) = map(int, input().split())
	arr = []
	ans = [[-1] * m for i in range(n)]
	mns = []
	for i in range(n):
		arr.append(list(map(int, input().split())))
		for j in range(m):
			mns.append((arr[i][j], i))
	mns.sort()
	pt = 0
	for i in range(m):
		ans[mns[pt][1]][i] = mns[pt][0]
		idx = arr[mns[pt][1]].index(mns[pt][0])
		arr[mns[pt][1]][idx] = -1
		pt += 1
	for i in range(n):
		pt = 0
		for j in range(m):
			if ans[i][j] == -1:
				while arr[i][pt] == -1:
					pt += 1
				ans[i][j] = arr[i][pt]
				pt += 1
	for ln in ans:
		print(*ln)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	main(_ + 1)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	lst_lst = []
	for _ in range(n):
		lst_lst.append(sorted(map(int, input().split())))
	ans = ['' for _ in range(n)]
	for _ in range(m):
		min_idx = min(range(len(lst_lst)), key=lambda x: lst_lst[x])
		lst_lst[min_idx] = lst_lst[min_idx][1:] + [lst_lst[min_idx][0]]
		for idx in range(n):
			ans[idx] += str(lst_lst[idx].pop()) + ' '
	print('\n'.join(ans))


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	lst = []
	for j in range(n):
		lst1 = list(map(int, input().split()))
		lst.append(lst1)
	dic = {}
	for k in range(n):
		dic[k] = []
	c = 0
	for g in range(m):
		ind = -1
		mi = 1000000000
		for f in range(n):
			lst2 = lst[f]
			if min(lst2) < mi:
				mi = min(lst2)
				ind = f
		for d in range(n):
			lst3 = lst[d]
			if d != ind:
				dic[d].append(max(lst3))
				lst[d].remove(max(lst3))
			else:
				dic[d].append(mi)
				lst3.remove(mi)
	for w in dic.keys():
		print(*dic[w])