Under construction

Still being built. Things may change

Box Puzzle

Time limit2sMemory limit128 MB

Summary
Place n^2 rotatable cube boxes into an n by n grid so touching side faces match and outward faces show 0, then output the arrangement and rotation counts.
Level

Medium6 of 10

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

Problem

There are n2n^2 cube-shaped boxes. Each box has an integer written on its top face and on each of its four side faces. Place all boxes into an n×nn \times n grid to complete the puzzle.

The placement must satisfy these conditions.

  1. A box may only be rotated parallel to the floor, so its top face always points upward.
  2. After all boxes are placed, the numbers on two touching side faces of adjacent boxes must be equal.
  3. A side face that points outside the grid must have the number 0.

The figure below illustrates a valid placement.

The number inside a circle is written on the top face of a box, and the numbers around it are written on the four side faces. Placing the 9 boxes as shown satisfies all conditions.

Given the numbers written on each box, arrange the boxes so that all conditions hold and determine how many times each box was rotated.

Input

The first line contains nn. (2≤n≤5)(2 \le n \le 5)

The next n2n^2 lines describe one box each. In each line, the first number is written on the top face. The following four numbers are the side-face numbers listed in clockwise order when viewed from above.

The top-face numbers are distinct positive integers not greater than n2n^2. Each side-face number is a nonnegative integer not greater than 9. The input is guaranteed to have at least one valid arrangement.

Output

First, print an n×nn \times n matrix containing the numbers written on the top faces of the placed boxes.

Then print an n×nn \times n matrix containing, for each placed box, how many clockwise rotations were made from its input orientation. Each rotation count must be an integer from 0 to 3.

Examples1

  1. Example 1

    Input
    3
    1 3 6 2 0
    2 5 0 0 2
    3 0 4 3 0
    4 0 8 5 4
    5 2 4 0 0
    6 5 6 9 6
    7 0 0 3 8
    8 9 2 0 4
    9 3 0 5 6
    
    Expected output
    3 4 7
    1 6 9
    5 8 2
    0 0 0
    0 0 0
    0 0 0