Another Puzzling Problem
InterviewTime limit1sMemory limit128 MB
Each jigsaw piece carries four integer edge labels; match opposite labels to place every piece in the N by N grid, then print the assembled picture.
- Level
Medium5 of 10
- Topics
- Implementation, Brute force, Matrix, Hash map
- Solved
- No attempts yet
Problem
Write a program that solves jigsaw puzzles. The input describes the size of the puzzle, the size of the pieces, and every piece. Each piece is drawn with ASCII characters. Your program must print the solved puzzle: all pieces assembled into their correct positions.
Input
The first line contains three integers , , and : the number of pieces along one side of the puzzle (a puzzle is always an square), the height of a piece, and the width of a piece. Every piece has the same size. The bounds are and . For example, 2 2 3 describes a puzzle whose pieces are each characters tall and characters wide.
The remaining input describes the pieces in arbitrary order. Each piece consists of its image — exactly lines of characters — followed by one line with four integers in the range : the shapes of the top, left, bottom, and right edges, in that order. A value of marks a straight (outer) edge. Two edges fit together exactly when their values are opposite and sum to (for example locks into , and into ). Pieces are never rotated, and no two pieces share the same four edge values (all pieces are distinct). A blank line separates consecutive pieces.
Spaces (ASCII code 32) are ordinary characters and may appear anywhere in a piece, including at the end of a line or as an entire line; they always appear in the input where they belong. Every piece is a solid rectangular block of characters (ASCII codes 32 to 127), so treat a space exactly like any other character.
Output
Print the solved puzzle. There is exactly one way to lay out the pieces: every outer edge (value ) lies on the border, the right edge of each piece and the left edge of its right-hand neighbour sum to , and the bottom edge of each piece and the top edge of the piece below it sum to . Print the resulting picture, which is lines of characters. The input always has exactly one solution.