Under construction

Still being built. Things may change

So I'll Max Out My Constructive Algorithm Skills

Time limit1sMemory limit1024 MB

Summary
Given an n by n grid whose heights are a permutation of 1 to n^2, find a path visiting every cell once where climbs are at most descents.
Level

Hard8 of 10

Topics
Matrix, Implementation, Greedy
Solved
No attempts yet

Problem

BaoBao the Witch is stuck in a maze with nn rows and nn columns. The height of the cell in row ii and column jj is hi,jh_{i,j}. To get out, BaoBao must find a path that visits each cell exactly once. She can only move to a neighboring cell that shares an edge with her current cell.

BaoBao is very lazy. Every time she climbs up (moves from a cell with a smaller height to a cell with a larger height), her happiness drops. Find a valid path so that the number of climbs is not more than the number of descents.

A valid path is a sequence (x1,y1),(x2,y2),…,(xn2,yn2)(x_1, y_1), (x_2, y_2), \ldots, (x_{n^2}, y_{n^2}) such that:

  • For all 1≤i≤n21 \le i \le n^2, 1≤xi,yi≤n1 \le x_i, y_i \le n.
  • For all 1≤i,j≤n21 \le i, j \le n^2 with i≠ji \ne j, (xi,yi)≠(xj,yj)(x_i, y_i) \ne (x_j, y_j).
  • For all 2≤i≤n22 \le i \le n^2, ∣xi−xi−1∣+∣yi−yi−1∣=1|x_i - x_{i-1}| + |y_i - y_{i-1}| = 1.
  • ∑i=2n2[hxi−1,yi−1<hxi,yi]≤∑i=2n2[hxi−1,yi−1>hxi,yi]\sum_{i=2}^{n^2} [h_{x_{i-1},y_{i-1}} < h_{x_i,y_i}] \le \sum_{i=2}^{n^2} [h_{x_{i-1},y_{i-1}} > h_{x_i,y_i}], where [P][P] is 1 when PP is true and 0 otherwise.

The heights of all cells form a permutation of 11 to n2n^2, so you only need to output the height of each cell along a valid path.

Input

There are multiple test cases. The first line contains TT (1≤T≤1001 \le T \le 100), the number of test cases.

Each test case starts with an integer nn (2≤n≤642 \le n \le 64), the size of the maze. The next nn lines each contain nn integers hi,1,hi,2,…,hi,nh_{i,1}, h_{i,2}, \ldots, h_{i,n} (1≤hi,j≤n21 \le h_{i,j} \le n^2). All integers in the input form a permutation of n2n^2.

Output

For each test case, print one line with n2n^2 integers separated by spaces. These are the heights of the cells in the order of a valid path. If several answers exist, print any of them. An answer always exists.

Examples1

  1. Example 1

    Input
    1
    2
    4 3
    2 1
    
    Expected output
    4 3 1 2