Under construction

Still being built. Things may change

The Grille

Time limit1sMemory limit128 MB

Summary
Simulate reading letters through the four rotations of a grille cipher grid to recover the plaintext for each test case.
Level

Medium5 of 10

Topics
Matrix, Simulation, Implementation
Solved
No attempts yet

Problem

In the 16th century there were no computers, yet messages still had to be protected from the wrong readers. Old tricks -- shaving a slave's head, writing the message on the scalp, waiting for the hair to grow back, and sending the slave through hostile territory -- could work, but they were painfully slow. Faster methods were needed. One of them is the grille cipher, first described by the Italian mathematician Girolamo Cardano.

Both enciphering and deciphering rely on a tool (the cipher key) called the grille, and both parties must own the same one. A grille is a square grid of N×NN \times N unit cells; some cells are solid and some are cut out to form holes.

Suppose a grille has mm holes. To encipher, write the first mm letters of the message into the holes, going row by row from top to bottom and, within each row, from left to right. Then rotate the grille 90 degrees clockwise and write the next mm letters into the holes in the same reading order. Rotate again and write another mm letters, then rotate once more and write the final mm letters. If any cells are still empty, fill them with random letters so the ciphertext looks more secure. Note that the grille is rotated, not the message.

To decipher, run the same procedure but read the letters through the holes instead of writing them.

Input

The input contains several test cases. Each test case describes one grille and one ciphertext.

Each test case begins with a line containing an integer NN (1≤N≤10001 \le N \le 1000), the size of the grille. The next NN lines describe the grille; each line contains exactly NN characters, each either # (solid material) or O (the uppercase letter O, a hole).

In practice a grille's holes are arranged so that no ciphertext position is ever used more than once. Here that is not guaranteed: after the rotations several holes may fall on the same ciphertext position. The deciphering procedure is nevertheless identical.

After the grille come another NN lines holding the ciphertext; each line contains exactly NN uppercase letters.

A line containing a single 0 follows the last test case.

Output

For each test case, print the deciphered message on its own line, with no spaces.

Examples1

  1. Example 1

    Input
    4
    ##O#
    #O#O
    ####
    ###O
    ARAO
    PCEM
    LEEN
    TURC
    3
    O#O
    ###
    O#O
    ABC
    DEF
    GHI
    0
    
    Expected output
    ACMCENTRALEUROPE
    ACGIACGIACGIACGI