Number Square
Time limit1sMemory limit1024 MB
Fill an N x N Latin square with 1..N given some pre-filled cells and inequalities between neighboring cells, choosing the lexicographically smallest valid board.
- Level
Hard8 of 10
- Topics
- Backtracking, Implementation, Greedy, Brute force
- Solved
- No attempts yet
Problem
In Number Square you place the numbers into an grid so that every number appears exactly once in each row and exactly once in each column (the grid is a Latin square).
In addition, for some pairs of neighbouring cells you are told which of the two must hold the larger number. Given the pre-filled cells and these ordering constraints, fill in the whole grid so that all of them are satisfied.
Input
The first line contains a single integer ().
The next lines each contain exactly characters and describe the starting position. Using 0-based indices, cell of the board is located at line , column .
- On the even-indexed lines (): the even-indexed columns hold the board cells — a digit
1–9for a pre-filled cell, or.if it is empty. The odd-indexed columns hold the horizontal ordering signs between two side-by-side cells:<,>, or.when there is no constraint. - On the odd-indexed lines (): the even-indexed columns hold the vertical ordering signs between two stacked cells:
^,V, or.when there is no constraint. The odd-indexed columns are always..
Each sign is an inequality that opens toward the larger number: < means the left cell is smaller than the right one, > means the left cell is larger, ^ means the upper cell is smaller than the lower one, and V means the upper cell is larger.
Output
It is guaranteed that at least one valid filling exists. Print the completed board as lines, each containing integers separated by single spaces.
If more than one valid filling exists, print the lexicographically smallest one, where a completed board is compared as the sequence obtained by reading its cells row by row from top to bottom and, within each row, from left to right.