import sys
#์์ ์
๋ ฅ
N,M = map(int,sys.stdin.readline().split())
_map = [list(map(int,sys.stdin.readline().split())) for _ in range(N)]
chickens = []
houses = []
# ์ง๊ณผ ์นํจ์ง ์ขํ ์ ์ฅ
for row in range(N):
for col in range(N):
if _map[row][col] == 2:
chickens.append([row,col])
elif _map[row][col] == 1:
houses.append([row,col])
selected = []
checked = [False]*(len(chickens))
ans = 1e9
def getMinDistance(selected):
minDistance = 0
for house in houses:
houseR = house[0]
houseC = house[1]
distance = 1e9
for storeNum in selected:
chicken = chickens[storeNum]
chickenR = chicken[0]
chickenC = chicken[1]
distance = min(distance,abs(houseR-chickenR)+abs(houseC-chickenC))
minDistance +=distance
return minDistance
def bt():
global ans
if len(selected) == M:
ans = min(ans,getMinDistance(selected))
return
for i in range(len(chickens)):
if checked[i] == True:
continue
if len(selected)>=1 and selected[-1] > i:
continue
selected.append(i)
checked[i] = True
bt()
selected.pop()
checked[i] = False
bt()
print(ans)
๋ฌธ์ ์ ๊ทผ ๋ฐฉ๋ฒ
1. ์นํจ ์ง ์ขํ๋ฅผ ๋ฐฐ์ด(์คํ)์ ๋ฃ์ด๋๋ค.
2. ์นํจ ์ง์ M๊ฐ ์ ํํด์ ์ป์ ์ ์๋ ๋ชจ๋ ์กฐํฉ์ ๊ตฌํด์ผ ํ๋ค.
2.1 python์ combinations ์ฌ์ฉ
2.2 โ ๋ฐฑํธ๋ํน ๋ฐฉ์ ์ฌ์ฉ
3. ๋ฐฑํธ๋ํน์ผ๋ก ๊ตฌํ selected ์คํ์๋ ์ขํ๊ฐ ๋ค์ด๊ฐ๋ ๊ฒ์ด ์๋ ๋ฐฐ์ด์ ์์น ์ ๋ณด๊ฐ ๋ค์ด๊ฐ
-> ex) ์นํจ์ง์ด 3๊ฐ์ด๊ณ 2๊ฐ๋ฅผ ์ ํํ ์ ์๋ค๋ฉด, (์นํจ ์ง ์ขํ = [a,b] [c,d] [e,f]
selected ์์๋ [ [a,b],[c,d] ] / [ [a,b],[e,f] ] / [ [c,d],[e,f] ] ์ด๋ฐ์์ผ๋ก ์ ์ฅ๋๋ ๊ฒ์ด ์๋
[0,1] [0,2] [1,2] ์ด๋ฐ์์ผ๋ก ์ ์ฅ
4. ๋ฐฑํธ๋ํน ์, checked ์ ์กฐ๊ฑด๋ฌธ์ผ๋ก ์ค๋ณต ์ ํ ์ ๊ฑฐ
5. ๋ฐฑํธ๋ํน์ผ๋ก ์นํจ์ง M๊ฐ๋ฅผ ์ ํํ๋ค๋ฉด, ๋์์ ์ต์ ์นํจ ๊ฑฐ๋ฆฌ๋ฅผ getMinDistance() ํจ์๋ก ๊ตฌํจ
-> ๋ก์ง ์งค๋ ์๊ทผํ ํท๊ฐ๋ ธ๋๋ฐ, ๋ณ์๋ฅผ ํ๋ํ๋ ํ์ด์ ์์ฑํ๋๋ ์ ์์ฑํ ์ ์์๋ค.