๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

โฌ› [Programmers] [Python] [Level3] ์—ฌํ–‰ ๊ฒฝ๋กœ

Dbswnstjd 2023. 5. 10. 11:36

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/43164/solution_groups?language=python3 

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 3๋‹จ๊ณ„ - ์—ฌํ–‰ ๊ฒฝ๋กœ
from collections import defaultdict
def solution(tickets):
    path = []
    graph = defaultdict(list)
    for (start, end) in tickets:
        graph[start].append(end)
    
    for airport in graph.keys():
        graph[airport].sort(reverse=True)

    stack = ['ICN']
    while stack:
        top = stack.pop()

        if top not in graph or not graph[top]:
            path.append(top)
        else:
            stack.append(top)
            stack.append(graph[top].pop())
    return path[::-1]

DFS ๋ฅผ ํ†ตํ•ด ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ด๋‹ค.