https://www.acmicpc.net/problem/15686
def get_dist(combi):
sum_dist = 0
for hy, hx in houses:
min_dist = float('inf')
for sy, sx in stores:
if (sy, sx) in combi:
min_dist = min(min_dist, abs(hy-sy) + abs(hx-sx))
sum_dist += min_dist
return sum_dist
# init
from itertools import combinations
import sys
read = sys.stdin.readline
n, m = map(int, read().split())
board = [list(map(int, read().split())) for _ in range(n)]
houses, stores = [], []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == 1:
houses.append((i, j))
elif board[i][j] == 2:
stores.append((i, j))
# start
min_dist = float('inf')
for combi in combinations(stores, m):
min_dist = min(min_dist, get_dist(set(combi)))
print(min_dist)