import java.io.*;
import java.util.*;
public class Main {
static int chickenD;
static int[][] select;
static List<int[]> home, chicken;
static int d;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb = new StringBuffer();
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
home = new ArrayList<int[]>();
chicken = new ArrayList<int[]>();
int[][] city = new int[N][N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
int n = Integer.parseInt(st.nextToken());
if (n == 1)
home.add(new int[] { i, j });
if (n == 2)
chicken.add(new int[] { i, j });
}
}
chickenD = Integer.MAX_VALUE;
for (int i = 1; i <= M; i++) {
select = new int[i][];
comb(0, 0, i);
}
System.out.println(chickenD);
br.close();
}
static void comb(int cnt, int start, int M) {
if (cnt == M) {
d = 0;
for (int i = 0; i < home.size(); i++) {
int[] h = home.get(i);
int minD = Integer.MAX_VALUE;
for (int j = 0; j < select.length; j++) {
int[] c = select[j];
int temp = Math.abs(h[0] - c[0]) + Math.abs(h[1] - c[1]);
minD = Math.min(temp, minD);
}
d += minD;
}
chickenD = Math.min(chickenD, d);
return;
}
for (int i = start; i < chicken.size(); i++) {
select[cnt] = chicken.get(i);
comb(cnt + 1, i + 1, M);
}
}
}