forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path7.py
36 lines (30 loc) Β· 1.01 KB
/
7.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from itertools import combinations
n, m = map(int, input().split())
chicken, house = [], []
for r in range(n):
data = list(map(int, input().split()))
for c in range(n):
if data[c] == 1:
house.append((r, c)) # μΌλ° μ§
elif data[c] == 2:
chicken.append((r, c)) # μΉν¨μ§
# λͺ¨λ μΉν¨ μ§ μ€μμ mκ°μ μΉν¨ μ§μ λ½λ μ‘°ν© κ³μ°
candidates = list(combinations(chicken, m))
# μΉν¨ 거리μ ν©μ κ³μ°νλ ν¨μ
def get_sum(candidate):
result = 0
# λͺ¨λ μ§μ λνμ¬
for hx, hy in house:
# κ°μ₯ κ°κΉμ΄ μΉν¨ μ§μ μ°ΎκΈ°
temp = 1e9
for cx, cy in candidate:
temp = min(temp, abs(hx - cx) + abs(hy - cy))
# κ°μ₯ κ°κΉμ΄ μΉν¨ μ§κΉμ§μ 거리λ₯Ό λνκΈ°
result += temp
# μΉν¨ 거리μ ν© λ°ν
return result
# μΉν¨ 거리μ ν©μ μ΅μλ₯Ό μ°Ύμ μΆλ ₯
result = 1e9
for candidate in candidates:
result = min(result, get_sum(candidate))
print(result)