QOJ.ac

QOJ

时间限制: 1 s 内存限制: 512 MB 总分: 100

#3166. 跳房子

统计

城里有一个新的艺术装置,它激发了你的灵感……去玩一个幼稚的游戏。该艺术装置由一个 $n \times n$ 的方格地砖矩阵组成。每个地砖上写有一个 $1$ 到 $k$ 之间的数字。你想在上面玩跳房子游戏。你希望从某个标号为 $1$ 的地砖开始,然后跳到某个标号为 $2$ 的地砖,接着跳到 $3$,以此类推,直到你到达某个标号为 $k$ 的地砖。你是一个优秀的跳跃者,所以你可以跳跃任意所需的距离。你必须恰好访问每个数字(从 $1$ 到 $k$)的地砖各一次。

完成一局跳房子游戏的最短总距离是多少?请使用曼哈顿距离:位于 $(x_1, y_1)$ 的地砖与位于 $(x_2, y_2)$ 的地砖之间的距离为 $|x_1 - x_2| + |y_1 - y_2|$。

输入格式

输入的第一行包含两个空格分隔的整数 $n$ ($1 \le n \le 50$) 和 $k$ ($1 \le k \le n^2$),其中艺术装置由一个 $n \times n$ 的矩阵组成,地砖上的数字范围为 $1$ 到 $k$。

接下来的 $n$ 行,每行包含 $n$ 个空格分隔的整数 $x$ ($1 \le x \le k$)。这就是艺术装置的布局。

输出格式

输出一个整数,表示从某个 $1$ 号地砖开始并以某个 $k$ 号地砖结束的最短路径的总长度;如果无法完成,则输出 $-1$。

样例

样例输入 1

10 5
5 1 3 4 2 4 2 1 2 1
4 5 3 4 1 5 3 1 1 4
4 2 4 1 5 4 5 2 4 1
5 2 1 5 5 3 5 2 3 2
5 5 2 3 2 3 1 5 5 5
3 4 2 4 2 2 4 4 2 3
1 5 1 1 2 5 4 1 5 3
2 2 4 1 2 5 1 4 3 5
5 3 2 1 4 3 5 2 3 1
3 4 2 5 2 5 3 4 4 2

样例输出 1

5

样例输入 2

10 5
5 1 5 4 1 2 2 4 5 2
4 2 1 4 1 1 1 5 2 5
2 2 4 4 4 2 4 5 5 4
2 4 4 5 5 5 2 5 5 2
2 2 4 4 4 5 4 2 4 4
5 2 5 5 4 1 2 4 4 4
4 2 1 2 4 4 1 2 4 5
1 2 1 1 2 4 4 1 4 5
2 1 2 5 5 4 5 2 1 1
1 1 2 4 5 5 5 5 5 5

样例输出 2

-1

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.