[IT]
[SW역량테스트준비] 치킨 배달
working_hard
2019. 10. 17. 23:38
728x90
import sys
sys.stdin = open('input.txt')
n,m = map(int,input().split())
a = [list(map(int,input().split())) for _ in range(n)]
chi,home = [],[]
select = []
def init():
global select
for i in range(n):
for j in range(n):
if a[i][j]==1:
home.append((i,j))
if a[i][j]==2:
chi.append((i,j))
select = [False]*len(chi)
# 집과 치킨집사이의 최소값을 구하고, 그 최소값을 모두 더한 최종 값이 가장 작은걸 구하면 된다.
def solve2(tmp_chi):
global ans
re = 0
for i in home:
hx,hy = i
tmp = 10**9
for j in tmp_chi:
cx,cy = j
tmp = min(tmp,abs(hx-cx)+abs(hy-cy))
re += tmp
ans = min(ans,re)
def solve(idx,cnt,d):
if cnt==m:
tmp = []
for i in range(d):
if select[i]:
x,y = chi[i]
tmp.append((x,y))
solve2(tmp)
return
for i in range(idx,d):
if not select[i]:
select[i] = True
solve(i+1,cnt+1,d)
select[i] = False
init()
ans = 10**9
solve(0,0,len(chi))
print(ans if ans!=10**9 else -1)