// Arup Guha
// 2/22/2020
// Solution to 2020 NAC Problem F: Hopscotch
// Written during contest and submitted on Kattis, commented later.

import java.util.*;

public class hopscotch50 {

	public static void main(String[] args) {
	
		// Get all of the input.
		Scanner stdin = new Scanner(System.in);
		int n = stdin.nextInt();
		int k = stdin.nextInt();
		ArrayList[] locs = new ArrayList[k+1];
		for (int i=0; i<=k; i++)
			locs[i] = new ArrayList<Integer>();
		
		// Specifically, locs[x] will store all grid locations which store the value x.
		for (int i=0; i<n*n; i++) {
			locs[stdin.nextInt()].add(i);
		}
		
		// Just marking if a number is missing in the grid or not.
		boolean possible = true;
		for (int i=1;i<=k; i++)
			if (locs[i].size() == 0)
				possible = false;
			
		// Initially we can't do it.
		int res = -1;
		
		if (possible) {
			
			// Set up our DP - dp[i][j], which is the fewest number of steps to get to the jth item storing value i, starting from anywhere.
			int[][] dp = new int[k+1][];
			for (int i=1; i<=k; i++) dp[i] = new int[locs[i].size()];
			
			// Loop through our space. We start at 2 because the cost to get to 1 is defined as 0.
			for (int i=2; i<=k; i++) {
				for (int j=0; j<dp[i].length; j++) {
					
					// Sentinel value which means we can't do it.
					dp[i][j] = 100000000;
				
					// get best for dp[i][j] - just getting to this slot.
					for (int prev=0; prev<dp[i-1].length; prev++) {
						int cur = dp[i-1][prev] + man(((ArrayList<Integer>)locs[i-1]).get(prev), ((ArrayList<Integer>)locs[i]).get(j),n);
						dp[i][j] = Math.min(dp[i][j], cur);
					}
				}
			}
			
			// We don't care which slot with k we end up at, so take the best.
			res = dp[k][0];
			for (int i=1; i<dp[k].length; i++)
				res = Math.min(res, dp[k][i]);
		}
		
		// Ta da!
		System.out.println(res);
	}
	
	// Returns the manhattan distance between locations a and b on an n by n grid.
	public static int man(Integer a, Integer b, int n) {
		return Math.abs(a/n - b/n) + Math.abs(a%n - b%n);
	}
}