#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int N, M;
int city[50][50];
int chicken_dist = 100000;
vector<pair<int, int>> houses;
vector<pair<int, int>> chickens;
vector<pair<int, int>> answer((13,13));
int find_dist() {
int dist;
int mini_dist;
int total = 0;
for (int i = 0; i < houses.size(); i++) {
mini_dist = 100000;
for (int j = 0; j < M; j++) {
dist = abs(houses[i].first - answer[j].first) + abs(houses[i].second - answer[j].second);
if (mini_dist > dist)
mini_dist = dist;
}
total += mini_dist;
}
return total;
}
void swap(int index1, int index2) {
pair<int, int> temp = chickens[index1];
chickens[index1] = chickens[index2];
chickens[index2] = temp;
}
void recursive(int index, int size) {
if (size == M) {
int temp_dist = find_dist();
if (chicken_dist > temp_dist)
chicken_dist = temp_dist;
return;
}
for (int i = index; i < chickens.size(); i++) {
if (chickens[i].first == -1)
continue;
answer[size] = chickens[i];
chickens[i].first = -1;
recursive(i, size + 1);
chickens[i].first = answer[size].first;
}
}
int main() {
cin >> N >> M;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> city[i][j];
if (city[i][j] == 1)
houses.push_back(make_pair(i, j));
else if (city[i][j] == 2)
chickens.push_back(make_pair(i, j));
}
}
recursive(0, 0);
cout << chicken_dist << endl;
return 0;
}