跳到主要内容
图灵 OJTURING / ONLINE JUDGE

#F1223. Vanya and Treasure

    ID: 1229 传统题 2000ms 256MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>数据结构动态规划图论最短路挑战难度共享题库Codeforces英文题面题目来源题面语言

Vanya and Treasure

题目描述

D. Vanya and Treasure
time limit per test
1.5 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Vanya is in the palace that can be represented as a grid n×m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type xp-1 contains a key that can open any chest of type x+1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.

Vanya starts in cell (1,1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1,c1) (the cell in the row r1 and column c1) and (r2,c2) is equal to |r1-r2|+|c1-c2|.

Input

The first line of the input contains three integers n, m and p (1≤n,m≤300,1≤pn·m)− the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively.

Each of the following n lines contains m integers aij (1≤aijp)− the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc=x). Also, it's guaranteed that there is exactly one chest of type p.

Output

Print one integer− the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p.

Examples
Input
3 4 3
2 1 1 1
1 1 1 1
2 1 1 3
Output
5
Input
3 3 9
1 3 5
8 9 7
4 6 2
Output
22
Input
3 4 12
1 2 3 4
8 7 6 5
9 10 11 12
Output
11


题目来源:fps-www.educg.net-codeforce-1-2833.xml.zip;FPS 共享题包,题包内第 704 题。保留原作者与原赛事署名。