import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
static int N = sc.nextInt(); // 배열 크기
static int[][] map = new int[N][N]; // 전체 지도
static boolean[][] result = new boolean[N][N];
static int whole = 0; // 전체 치킨 집
static int M = sc.nextInt(); // 남아있는 치킨 집
static ArrayList<Integer> a;
static ArrayList<Integer> b;
static ArrayList<Integer> c;
static int min = Integer.MAX_VALUE;
static int sumMin = Integer.MAX_VALUE;
public static void main(String[] args) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
map[i][j] = sc.nextInt();
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] == 2)
whole++;
}
}
a = new ArrayList<>();
b = new ArrayList<>();
c = new ArrayList<>();
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] == 2) {
a.add(i);
b.add(j);
}
}
}
comb(0, 0);
System.out.println(Collections.min(c));
}
private static void comb(int index, int cnt) {
int sum = 0;
if (cnt == M) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] == 1) {
min = Integer.MAX_VALUE;
for (int k = 0; k < N; k++) {
for (int l = 0; l < N; l++) {
if (map[k][l] == 2) {
if (result[k][l]) {
int dis = distance(i, k, j, l);
if (min > dis)
min = dis;
}
}
}
}
sum +=min;
}
}
}
c.add(sum);
return;
}
if (index == whole)
return;
result[a.get(index)][b.get(index)] = true;
comb(index + 1, cnt + 1);
result[a.get(index)][b.get(index)] = false;
comb(index + 1, cnt);
}
static int distance(int x1, int x2, int y1, int y2) {
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
}