Puzzle

Time limit1sMemory limit128 MB

Summary
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 n×nn \times n board. The field in row ii and column jj (1≤i,j≤n1 \le i, j \le n) has coordinates (i,j)(i, j) and holds a piece numbered p(i,j)p(i, j), where 1≤p(i,j)≤n21 \le p(i, j) \le n^2. Each number from 11 to n2n^2 appears on exactly one piece.

Coordinates of the fields

The puzzle is solved when, for every 1≤i,j≤n1 \le i, j \le n, field (i,j)(i, j) holds the piece numbered j+(i−1)×nj + (i - 1) \times n.

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 kk to the right by ll fields (1≤l≤n−11 \le l \le n-1) turns the board into p′(i,j)={p(i, j+n−l)i=k, j≤lp(i, j−l)i=k, j>lp(i,j)i≠kp'(i,j) = \begin{cases} p(i,\, j+n-l) & i = k,\ j \le l \\ p(i,\, j-l) & i = k,\ j > l \\ p(i,j) & i \ne k \end{cases} Shifting a column down by ll 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 nn, the side length of the board (2≤n≤2002 \le n \le 200). Each of the next nn lines describes the initial configuration; line i+1i+1 contains p(i,1),p(i,2),…,p(i,n)p(i, 1), p(i, 2), \ldots, p(i, n) separated by single spaces. The values form a permutation of 1…n21 \ldots n^2.

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.

Examples3

  1. Example 1

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

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

    Input
    3
    2 1 3
    4 5 6
    7 8 9
    
    Expected output
    NO