Hopscotch 500

아직 제출이 없습니다시간 제한2초메모리 제한1024 MB

문제

Do you remember the new art installation from NAC 2020? Well, that artist is at it again, on a grander scale this time, and the new artwork still inspires you---to play a childish game. The art installation consists of a floor with a square matrix of tiles. Each tile holds a single number from 11 to kk.

You want to play hopscotch on it! You want to start on some tile numbered 11, then hop to a tile numbered 22, then 33, and so on, until you reach a tile numbered kk.

Instead of the usual Euclidean distance, define the distance between the tile at (x_1,y_1)(x\_1,y\_1) and the tile at (x_2,y_2)(x\_2,y\_2) as: \[\min\left[(x_1-x_2)^2, (y_1-y_2)^2\right]\] You want to hop the shortest total distance overall, using this new distance metric. Note that a path with no hops is still a path, and has length 00. What is the length of the shortest path?

입력

The first line of input contains two space-separated integers nn (1n5001 \le n \le 500) and kk (1kn21\le k\le n^2), where the art installation consists of an n!×!nn\\!\times\\! n matrix with tiles having numbers from 11 to kk.

Each of the next nn lines contains nn space-separated integers xx (1xk1 \le x \le k). These are the numbers in the art installation.

출력

Output a single integer, which is the total length of the shortest path from any 11 tile to any kk tile using our distance metric, or 1-1 if no such path exists.