Rotating Rings

Time limit1sMemory limit128 MB

Summary
Given square grids, decide whether each can be turned into row-major sorted order using only independent rotations of each concentric ring.
Level

Medium5 of 10

Topics
Array, Simulation, Implementation, Matrix
Solved
No attempts yet

Problem

Any square grid can be viewed as one or more concentric rings, one inside another. For example, as shown in figure (a), a 5×55 \times 5 grid is made of three rings, numbered 11, 22, and 33 from the outside inward. A square grid of size NN is said to be sorted if it contains the values from 11 to N2N^2 in row-major order, as shown in figure (b) for N=4N = 4.

We want to decide whether a given square grid can be sorted using only ring rotations. Each ring may be rotated by any number of positions, clockwise or counter-clockwise, independently of the other rings. For example, the grid in figure (c) can be sorted by rotating the outer ring two positions counter-clockwise and the second ring one position clockwise.

For each grid, determine whether it can be sorted in this way.

Input

The input consists of one or more test cases. Each test case begins with a line containing an integer NN, the size of the grid. The next NN lines each contain NN integers giving the grid values in row-major order.

You may assume 0<N≤10000 < N \le 1000, and every grid value is a natural number at most 10610^6.

The input ends with a line containing N=0N = 0, which must not be processed.

Output

For each test case, print a single line in the format:

k. result

where kk is the test case number (starting from 11), followed by a period and a single space, and result is YES if the grid can be sorted using only ring rotations, or NO otherwise.

Examples1

  1. Example 1

    Input
    4
    9 5 1 2
    13 7 11 3
    14 6 10 4
    15 16 12 8
    3
    1 2 3
    5 6 7
    8 9 4
    0
    
    Expected output
    1. YES
    2. NO