Rotating Rings
Time limit1sMemory limit128 MB
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 grid is made of three rings, numbered , , and from the outside inward. A square grid of size is said to be sorted if it contains the values from to in row-major order, as shown in figure (b) for .
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 , the size of the grid. The next lines each contain integers giving the grid values in row-major order.
You may assume , and every grid value is a natural number at most .
The input ends with a line containing , which must not be processed.
Output
For each test case, print a single line in the format:
k. result
where is the test case number (starting from ), 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.