Under construction

Still being built. Things may change

Bell Ringing

Time limit2sMemory limit256 MB

Summary
Print all permutations of 1 to n in the recursive insertion order where bell n sweeps each row left to right or right to left.
Level

Easy3 of 10

Topics
Recursion, Implementation
Solved
No attempts yet

Problem

Method ringing is a way of ringing church bells, common in England. Suppose there are nn bells with nn different pitches. The bell highest in pitch gets number 1, the second highest gets number 2, and so on. Ringing all nn bells in some order, each of them exactly once, gives one row. For n=6n = 6, the orders 1, 2, 3, 4, 5, 6 and 6, 3, 2, 4, 1, 5 are two different rows.

A performance is ideal when every possible row appears in it exactly once. Physics limits which rows can follow each other. A bell that has been rung carries considerable inertia, and the ringer can speed up or slow down its cycle only a little. Therefore the position of each bell can change by at most one between two consecutive rows.

The figure below shows a performance that respects the inertia of the bells but is not ideal. The trajectory of bell 1 is drawn in blue and the trajectory of bell 2 is drawn in brown.

Given nn, print an ideal performance whose first row is 1, 2, ..., nn.

Input

The first and only line contains an integer nn (1≤n≤81 \le n \le 8).

Output

Many ideal performances exist for the same nn, so exactly one of them is accepted, defined as follows.

  • For n=1n = 1 the sequence is the single row 1.
  • Let R1,R2,…,R(n−1)!R_1, R_2, \dots, R_{(n-1)!} be the sequence for n−1n - 1. Build the sequence for nn by replacing each RiR_i, in order, with nn rows: insert bell nn into each of the nn possible positions of RiR_i. When ii is odd, go from the rightmost position to the leftmost one. When ii is even, go from the leftmost position to the rightmost one.

Print the n!n! rows of that sequence, one row per line. Separate the nn numbers of a row with single spaces.

Examples3

  1. Example 1

    Input
    1
    
    Expected output
    1
    
  2. Example 2

    Input
    2
    
    Expected output
    1 2
    2 1
    
  3. Example 3

    Input
    3
    
    Expected output
    1 2 3
    1 3 2
    3 1 2
    3 2 1
    2 3 1
    2 1 3