ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

15686๋ฒˆ: ์น˜ํ‚จ ๋ฐฐ๋‹ฌ

ํฌ๊ธฐ๊ฐ€ N×N์ธ ๋„์‹œ๊ฐ€ ์žˆ๋‹ค. ๋„์‹œ๋Š” 1×1ํฌ๊ธฐ์˜ ์นธ์œผ๋กœ ๋‚˜๋ˆ„์–ด์ ธ ์žˆ๋‹ค. ๋„์‹œ์˜ ๊ฐ ์นธ์€ ๋นˆ ์นธ, ์น˜ํ‚จ์ง‘, ์ง‘ ์ค‘ ํ•˜๋‚˜์ด๋‹ค. ๋„์‹œ์˜ ์นธ์€ (r, c)์™€ ๊ฐ™์€ ํ˜•ํƒœ๋กœ ๋‚˜ํƒ€๋‚ด๊ณ , rํ–‰ c์—ด ๋˜๋Š” ์œ„์—์„œ๋ถ€ํ„ฐ r๋ฒˆ์งธ ์นธ

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ํฌ๊ธฐ๊ฐ€ 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
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€