8600: Fall Guys-Perfect Match

内存限制:1024 MB 时间限制:12 S 标准输入输出
题目类型:传统 评测方式:文本比较 上传者:
提交:2 通过:1

题目描述

In the famous game "Fall Guys:Ultimate Knockout", there's a level called "Perfect Match". We have simplified the rule of the game as follows: You stand on an n×n grid and there are m kinds of fruits. Also, each grid is labeled with some kind of fruit. It is guaranteed that each kind of fruit appears on at least 1 and at most 20 grids. You can choose to stand on any grid initially, then a fruit will appear on the big screen in the game, you need to run to a grid such that the fruit labeled on it is the same as the fruit on the screen, within the countdown. In the game, you can only move horizontally or vertically, i.e. if you stand on (x1,y1and move to (x2,y2), the distance you move is ∣x1−x2∣+∣y1−y2.

You want to select a grid to stand on initially, to minimize the distance you need to move in the worst case of all m possible fruits to appear on the big screen, so that hopefully you will not be knocked out even in the worst case! Calculate this minimized distance.

输入格式

The first line contains two integers n,m(1≤n≤1000,1≤m≤n2), denoting the size of the grid and the kinds of fruits, respectively.
The n lines follow, where the i-th line contains n integers ai,1,ai,2,...,ai,n(1≤ai,j≤m), denoting the fruits on the i-th row of the n×n grid.
It is guaranteed that for each 1≤xm, x appears at least 1 and at most 20 times in the matrix a.

输出格式

Output an integer in one line, denoting the answer.

输入样例 复制

2 3
1 2
1 3

输出样例 复制

1