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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

10971๋ฒˆ: ์™ธํŒ์› ์ˆœํšŒ 2

์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. (2 ≤ N ≤ 10) ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ๋น„์šฉ ํ–‰๋ ฌ์ด ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ–‰๋ ฌ์˜ ์„ฑ๋ถ„์€ 1,000,000 ์ดํ•˜์˜ ์–‘์˜ ์ •์ˆ˜์ด๋ฉฐ, ๊ฐˆ ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ๋Š” 0์ด ์ฃผ์–ด์ง„๋‹ค. W[i][j]๋Š” ๋„์‹œ i์—์„œ j

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ์ด ๋ฌธ์ œ๋Š” ๊ฐ ๋„์‹œ์— ๋Œ€ํ•ด ๊ฐ€์ค‘์น˜๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ ๋ชจ๋“  ๋„์‹œ๋ฅผ ์ˆœํšŒํ•˜๋˜, ์ตœ์†Œ ๊ฐ’์œผ๋กœ ์ˆœํšŒํ•˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. ๋ณดํ†ต ์ด๋Ÿฌํ•œ ๋ฌธ์ œ๋Š” DFS๋ฅผ ํ†ตํ•ด ๋ฐฉ๋ฌธํ•œ ๊ฒฝ๋กœ๋ฅผ ๊ธฐ๋กํ•ด๋‘๊ณ , ๊ฐ€๋Šฅํ•œ ๊ฒฝ๋กœ๋ฅผ ๋ชจ๋‘ ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ‘ผ๋‹ค. ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์œผ๋กœ๋Š” 1 - 2 - 4 - 3 - 1๊ณผ ๊ฐ™์€ ๋ฐฉ๋ฌธ ์ˆœ์„œ๋ฅผ ์ˆœ์—ด๋กœ ๊ตฌํ•œ ํ›„์— ๊ณ„์‚ฐํ•˜๋Š” ๋ฐฉ์‹๋„ ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค.

 ํ•˜์ง€๋งŒ ์ˆœ์—ด์„ ๊ณ„์‚ฐํ•˜๊ณ  ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์€ ์ต์ˆ™ํ•˜์ง€ ์•Š์•„, DFS๋กœ ๋ฐฉ๋ฌธ ๊ฐ€๋Šฅํ•œ ๊ฒฝ๋กœ๋ฅผ ํƒ์ƒ‰ํ•˜๊ณ , ์žฌ๊ท€ ํ˜ธ์ถœ์˜ depth๊ฐ€ 0์ด ๋˜๋ฉด ๋ฐฉ๋ฌธํ•œ ๊ฒฝ๋กœ์˜ ๊ฐ’์„ ๊ธฐ๋กํ•˜๋„๋ก ํ•˜์˜€๋‹ค. depth๊ฐ€ 0์ด ๋œ๋‹ค๋Š” ๊ฒƒ์€ ๋‹ค์‹œ ์›์ ์œผ๋กœ ๋Œ์•„์™”๋‹ค๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค.

 

 

์ฝ”๋“œ

DFS๋ฅผ ์ด์šฉํ•œ ํ’€์ด

from sys import stdin


def dfs(cur_node, cost):
    global answer

    if not cur_node and all(visited):
        answer = \
            cost if answer is None else min(answer, cost)
    else:
        for next_node in range(n):
            if cities[cur_node][next_node] and not visited[next_node]:
                visited[next_node] = True
                dfs(next_node, cost + cities[cur_node][next_node])
                visited[next_node] = False

if __name__ == '__main__':
    answer = None
    n = int(stdin.readline())
    cities = [list(map(int, stdin.readline().split())) for _ in range(n)]
    visited = [False] * n
    dfs(0, 0)
    print(answer)

 Python3๋กœ ์ œ์ถœํ•  ๊ฒฝ์šฐ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. PyPy3๋กœ ์ œ์ถœํ•˜๋ฉด ์‹œ๊ฐ„ ๋‚ด์— ํ†ต๊ณผํ•˜๋ฉฐ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐ ํ•  ์ˆ˜ ์žˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€