Under construction

Still being built. Things may change

Square Grid Puzzle

Time limit1sMemory limit1024 MB

Summary
Sort an N by N grid into row-major order using moves that send the top row to the bottom or the left column to the right, in fewer than 3N moves.
Level

Hard8 of 10

Topics
Simulation, Matrix, Implementation
Solved
No attempts yet

Problem

In this puzzle, you get a 00-indexed N×NN \times N square grid of distinct integers from 00 to N×N−1N \times N - 1, inclusive. The goal is to reach the ordered state where the number in row ii and column jj equals i×N+ji \times N + j for every 0≤i,j<N0 \le i, j < N. You can reach this goal with two types of moves:

  • D move (down): written as "D a[0]a[0] a[1]a[1] …\dots a[N−1]a[N - 1]", where a[0],a[1],…,a[N−1]a[0], a[1], \dots, a[N - 1] is a rearrangement of the numbers in the top row. The move removes the top row and adds a new row at the bottom of the grid. The new row holds a[0]a[0] through a[N−1]a[N - 1] from left to right.
  • R move (right): written as "R b[0]b[0] b[1]b[1] …\dots b[N−1]b[N - 1]", where b[0],b[1],…,b[N−1]b[0], b[1], \dots, b[N - 1] is a rearrangement of the numbers in the leftmost column. The move removes the leftmost column and adds a new column at the right of the grid. The new column holds b[0]b[0] through b[N−1]b[N - 1] from top to bottom.

A rearrangement changes only the order of the numbers, without adding or removing any of them. It may also keep the original order.

For example, suppose the current grid is:

Row/Column001122
00224466
11881155
22773300

The move "D 66 22 44" produces:

Row/Column001122
00881155
11773300
22662244

The move "R 22 88 77" instead gives:

Row/Column001122
00446622
11115588
22330077

For N=3N = 3, the target grid is:

Row/Column001122
00001122
11334455
22667788

You aim to solve the puzzle with fewer than 3×N3 \times N moves. You can still earn partial points with more moves or without solving the puzzle.

Input

The first line contains a single integer NN. The following NN lines describe the initial grid, with NN numbers on each line.

Output

The first line contains a single integer MM, the number of moves. Each of the following MM lines contains one move.

Constraints

2≤N≤92 \le N \le 9. Each value of NN from 22 to 99 has the same number of test cases.

Examples2

  1. Example 1

    Input
    3
    1 4 2
    3 7 5
    6 8 0
    
    Expected output
    4
    R 3 6 1
    D 2 3 4
    D 5 6 7
    R 2 5 8
    
  2. Example 2

    Input
    2
    2 1
    0 3
    
    Expected output
    0