So I'll Max Out My Constructive Algorithm Skills
Time limit1sMemory limit1024 MB
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 rows and columns. The height of the cell in row and column is . 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 such that:
- For all , .
- For all with , .
- For all , .
- , where is 1 when is true and 0 otherwise.
The heights of all cells form a permutation of to , 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 (), the number of test cases.
Each test case starts with an integer (), the size of the maze. The next lines each contain integers (). All integers in the input form a permutation of .
Output
For each test case, print one line with 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.