Towers
Time limit10sMemory limit256 MB
Fill an n by n Latin square with heights 1 to n that matches fixed cells and border visibility counts, printing the smallest solution or no.
- Level
Medium6 of 10
- Topics
- Backtracking, Brute force
- Solved
- No attempts yet
Problem
Place one tower in every cell of an grid. Each tower has an integer height between and , and no two towers of the same height may share a row or a column, so every row and every column holds each height from to exactly once.
A puzzle adds two kinds of constraints.
First, some cells of the grid have a required height, and the tower placed there must have that height.
Second, some positions around the border carry a number. That number is the exact count of towers you see when you look into the grid along that row or column from that side. A taller tower completely hides every shorter tower behind it, so a tower is visible only when it is taller than every tower between it and the viewer.
Find a placement that satisfies every constraint.
Input
The first line has the number of puzzles . ()
Each puzzle starts with a line holding the grid size (), followed by lines of characters each.
The first of those lines is the top border and the last one is the bottom border. The first character of each of the middle lines is the left border and the last character is the right border. A digit on the border is the number of towers visible from that direction, and '-' means that direction has no constraint. The four corners are always '-'.
The inner characters of each of the middle lines are the cells of the grid. A digit is the required height of the tower in that cell, and '-' means the height is not fixed.
Every character of a puzzle is either '-' or a digit between and .
Output
For each puzzle print the answer as lines of digits, then print one blank line.
If several placements satisfy the constraints, print the lexicographically smallest one. Compare two answers as the digit string formed by reading the grid top to bottom and each row left to right.
If the puzzle has no solution, print the single word no, then print one blank line.