Puzzle
Time limit1sMemory limit128 MB
Given an n by n permutation board, decide whether row and column cyclic shifts can turn it into the target board where cell (i,j) holds (i-1)*n+j.
- Level
Medium7 of 10
- Topics
- Math, Implementation, Matrix, Simulation
- Solved
- No attempts yet
Problem
The king of Byteland received a jigsaw puzzle as a gift. The puzzle is an board. The field in row and column () has coordinates and holds a piece numbered , where . Each number from to appears on exactly one piece.

Coordinates of the fields
The puzzle is solved when, for every , field holds the piece numbered .
Only two kinds of moves are allowed:
- Row shift: cyclically shift all pieces in one row a chosen number of fields to the right.
- Column shift: cyclically shift all pieces in one column a chosen number of fields down.
Formally, shifting row to the right by fields () turns the board into Shifting a column down by fields is defined analogously, moving pieces toward larger row indices.
The king solved his own puzzle, but he wonders which starting configurations are solvable in the first place. Given a configuration, decide whether it can be solved using only the moves above.
Input
The first line contains one integer , the side length of the board (). Each of the next lines describes the initial configuration; line contains separated by single spaces. The values form a permutation of .
Output
Print a single line: YES if the board can be solved using the allowed moves, or NO otherwise.
Hint
A sequence of row shifts and column shifts turns one configuration into another, as illustrated below.
