

const { notDeepEqual } = require("assert");
const { count } = require("console");
const fs = require("fs");
const { nextTick } = require("process");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./예제.txt";
let input = fs.readFileSync(filePath).toString().trim().split('\n');
// const fs = require('fs');
// let input = fs.readFileSync("/dev/stdin").toString().trim().split('\n');
const [N, M]=input.shift().split(' ').map((el)=>+el)
let array=[];
for (let i=0;i<N;i++){
array.push(input[i].split(' ').map((el)=>+el))
}
// 치킨집 위치
let chicken=[]
// 집 위치
let house=[]
for (let i=0;i<N;i++){
for (let j=0;j<array[0].length;j++){
if (array[i][j]===1){
house.push([i,j]);
}else if (array[i][j]===2){
chicken.push([i,j])
}
}
}
// 치킨 거리 계산
const chickenDistance=(house, chicken)=>{
return Math.abs(house[0]-chicken[0])+Math.abs(house[1]-chicken[1]);
}
// 치킨집 중 M개를 뽑아야 함.
const combination=(array, selectM)=>{
let combinationArray2=[];
if (selectM===1){
return array.map((el)=>[el])
}
array.forEach((current, index, calledArray)=>{
let rest=calledArray.slice(index+1);
let combinationResult=combination(rest,selectM-1);
let attached=combinationResult.map((el)=>[current,...el]);
combinationArray2.push(...attached)
})
return combinationArray2;
}
let length = Array.from({length:chicken.length}, (_,i) => i);
let combintationArray = combination(length, M);
let rArr = [];
combintationArray.forEach(el => {
let total = 0;
for(let [a, b] of house){
let min = 99999999999;
el.forEach(el2 => {
let val = Math.abs(chicken[el2][0] - a) + Math.abs(chicken[el2][1] - b);
if(min > val) min = val;
})
total += min;
}
rArr.push(total);
})
console.log(Math.min(...rArr));