ํฐ์คํ ๋ฆฌ ๋ทฐ
728x90
๋ฐ์ํ
๋ฌธ์
๋ฌธ์ ํ์ด
ํฌ๊ธฐ๊ฐ NxN์ธ ๋์์์ ์นํจ์ง๊ณผ ์ง์ด ์์ ๋, ์นํจ ์ง M๊ฐ๋ง ์ ํํ๊ณ ๋๋จธ์ง๋ ํ์ ํ์ฌ์ผ ํ๋ค. ์ด๋ ๋์์ ์นํจ ๊ฑฐ๋ฆฌ๊ฐ ๊ฐ์ฅ ์๊ฒ ๋๋ ๊ฒฝ์ฐ๋ฅผ ๋ฐํํ๋ ๋ฌธ์ ์ด๋ค. ๋ฌธ์ ๋ฅผ ํ๊ธฐ ์ํด์ ์๋์ ๊ฐ์ ๋ก์ง์ ์์ฑํ๋ฉด ํ ์ ์๋ค.
- ์ ๋ ฅ๋ NxN์์ ๋์์์ ์นํจ ์ง๊ณผ ์ง์ ์ขํ๋ฅผ ์ฐพ๋๋ค.
- DFS๋ฅผ ํตํด M๊ฐ์ ์นํจ์ง์ ์ ํํ๊ณ , M๊ฐ๊ฐ ์ ํ๋ ๊ฒฝ์ฐ ๊ฑฐ๋ฆฌ๋ฅผ ๊ณ์ฐํ๋ค.
- ๋ฌธ์ ์์ ๊ฑฐ๋ฆฌ๋ฅผ ๊ณ์ฐํ๋ ์์ ๋งจํํผ ๊ฑฐ๋ฆฌ์ด๋ค.
์ฝ๋
from sys import stdin
from math import inf
def manhattan_dist(h, c):
return abs(h[X] - c[X]) + abs(h[Y] - c[Y])
def dfs(idx, selected):
global answer
if idx > len(chicken):
return
if selected == m:
sum_distance = 0
for house in houses:
min_distance = inf
for c_idx, value in enumerate(chicken):
if not check[c_idx]:
continue
min_distance = min(min_distance, manhattan_dist(house, value))
sum_distance += min_distance
answer = min(answer, sum_distance)
return
check[idx] = True
dfs(idx + 1, selected + 1)
check[idx] = False
dfs(idx + 1, selected)
if __name__ == '__main__':
X, Y = 0, 1
n, m = map(int, stdin.readline().split())
graph = [list(map(int, stdin.readline().split())) for _ in range(n)]
houses, chicken = [], []
answer = inf
for i in range(n):
for j in range(n):
if graph[i][j] == 1:
houses.append([i + 1, j + 1])
elif graph[i][j] == 2:
chicken.append([i + 1, j + 1])
check = [False] * (len(chicken) + 1)
dfs(0, 0)
print(answer)
ํ์ด์ฌ์ ๊ฒฝ์ฐ `itertools.combination`์ ์ฌ์ฉํ์ฌ ํ ์ ์์ง๋ง, ์ผ์ฑ SW ์ญ๋ ํ ์คํธ์ ๊ฒฝ์ฐ `itertools`๋ฅผ ์ฌ์ฉํ ์ ์๊ธฐ์, DFS๋ก ๋ฌธ์ ๋ฅผ ํ์๋ค.
728x90
๋ฐ์ํ
'๐จโ๐ป ์ฝ๋ฉํ ์คํธ > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค: 12869 ๋ฎคํ๋ฆฌ์คํฌ (0) | 2020.09.25 |
---|---|
๋ฐฑ์ค: 16197 ๋ ๋์ (0) | 2020.09.25 |
๋ฐฑ์ค: 2210 ์ซ์ํ ์ ํ (0) | 2020.09.24 |
๋ฐฑ์ค: 3568 iSharp (0) | 2020.09.24 |
๋ฐฑ์ค: 15662 ํฑ๋๋ฐํด (2) (0) | 2020.09.23 |
๋๊ธ
๊ธ ๋ณด๊ดํจ
์ต๊ทผ์ ์ฌ๋ผ์จ ๊ธ
์ต๊ทผ์ ๋ฌ๋ฆฐ ๋๊ธ