Dominosa
Time limit1sMemory limit128 MB
Reconstruct the domino tiling of an n by n+1 grid where each unordered symbol pair appears exactly once.
- Level
Medium7 of 10
- Topics
- Backtracking, Brute force
- Solved
- No attempts yet
Problem
With different symbols there are unordered pairs of symbols, counting a pair of two equal symbols as one of them. One domino per pair makes a full set, and a full set covers exactly squares, so it fits an by rectangle with no gaps and no overlaps.
Lay a full set out that way, erase the edges of the dominoes, and keep only the symbol written in each square. What is left is a puzzle. On the left of the picture below is an original layout of the 28 dominoes made from the seven numbers 0 to 6, and on the right is the same layout with the edges erased.

Read the puzzle and recover the original layout. The layout always exists and it is unique.
Input
The input holds several puzzles.
The first line of a puzzle has an integer (). The next lines each hold characters separated by single spaces. The characters come from the first lowercase letters, a through the th letter of the alphabet.
The grid was built by placing each of the unordered pairs exactly once, and only one placement matches the grid.
A line holding a single 0 ends the input.
Output
For each puzzle print the recovered layout in the same format as the input, except that the two characters of a horizontal domino are joined by an equals sign (=) instead of a space. Every other gap stays a single space.
Print one blank line between consecutive grids, and no blank line after the last grid.