Jumping Grids
题号:NC294489
时间限制:C/C++/Rust/Pascal 1秒,其他语言2秒
空间限制:C/C++/Rust/Pascal 256 M,其他语言512 M
64bit IO Format: %lld

题目描述

Xiaoming is a little boy.

One day, he finds a n \times n grids on his school's playground. For each grid, there is am integer between 1 and k written on it.

His classmate invites him to play with the grids. His task is to jump on the grids one by one. The first step he should stand on the grid in which number 1 is written (any one is ok), then he has to jump onto one of the grids with number 2 written on it, then he has to jump onto the grids with number 3, and so on, until he jumps onto the grid with number k.

The cost of jumping from grid (x_1,y_1) to (x_2, y_2) is the Manhattan distance between them, that is, |x_1 - x_2| + |y_1 - y_2|.

Xiaoming wonders if he can finish the task. If so, what is the minimum total cost to finish the task?

输入描述:

The first line contains two integers n, k (2 \le n \le 50, 2 \le k \le n^2).

The next input n \times n integers, denoting the grids. Each integer is between 1 and k.

输出描述:

If Xiaoming cannot finish the task, print -1. Otherwise, print the minimum total cost to finish the task.
示例1

输入

复制
4 14
2 4 5 1
3 6 8 7
9 10 14 13
2 4 11 12

输出

复制
21
示例2

输入

复制
5 15
4 5 1 9 10
15 12 1 3 2
2 7 13 11 8
8 9 11 3 6
12 14 14 8 2

输出

复制
40
示例3

输入

复制
2 2
1 1
1 1

输出

复制
-1