A Puzzling Problem

Interview

Time limit1sMemory limit128 MB

Summary
Place up to 5 fixed-orientation polyomino pieces, each labeled by index, to tile a 4x4 square exactly, printing the lexicographically smallest labeled grid or a failure message.
Level

Medium6 of 10

Topics
Backtracking, Brute force, Implementation, Matrix
Solved
No attempts yet

Problem

Write a program that takes from 1 to 5 puzzle pieces and, if possible, arranges them to form a 4-by-4 square.

The pieces may not be rotated or flipped: each piece keeps its original orientation. Every piece must be used, and together the pieces must cover the 4×4 square exactly, with no gaps and no overlaps. A set of pieces may have more than one arrangement that works, exactly one, or none at all.

Input

The input describes several puzzles (sets of puzzle pieces).

The first line of each puzzle contains the number of pieces in that puzzle. Each piece is then given by a line with two integers, the number of rows and the number of columns of the piece, followed by that many lines describing the piece's shape. A shape line consists of 0 and 1 characters: a 1 marks a solid cell of the piece, and a 0 is only a placeholder. For example, a piece written as

2 3
111
101

is 2 rows by 3 columns and has its solid cells forming that shape.

Pieces are numbered in the order they appear: the first piece in a puzzle is piece #1, the next is piece #2, and so on. Every piece is valid and is no larger than 4 rows by 4 columns.

After the last piece of one puzzle, the next line gives the number of pieces in the following puzzle, and so on. A value of 0 in place of a piece count marks the end of the input.

Output

For each puzzle, build a 4-row by 4-column square. Replace the solid cells of piece #1 with the character 1, the solid cells of piece #2 with 2, and so on, then print the four resulting rows.

If more than one valid square can be formed, output the lexicographically smallest one: read the grid as the 16-character string obtained by concatenating the four rows from top to bottom, each row from left to right, and choose the arrangement whose string is smallest.

If no valid square can be formed, print No solution possible instead. Separate the outputs of consecutive puzzles with a single blank line.

Examples2

  1. Example 1

    Input
    4
    2 3
    111
    101
    4 2
    01
    01
    11
    01
    2 1
    1
    1
    3 2
    10
    10
    11
    4
    1 4
    1111
    1 4
    1111
    1 4
    1111
    2 3
    111
    001
    5
    2 2
    11
    11
    2 3
    111
    100
    3 2
    11
    01
    01
    1 3
    111
    1 1
    1
    0
    
    Expected output
    1112
    1412
    3422
    3442
    
    No solution possible
    
    1133
    1153
    2223
    2444
    
  2. Example 2

    Input
    1
    4 4
    1111
    1111
    1111
    1111
    0
    
    Expected output
    1111
    1111
    1111
    1111