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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์—ฌํ–‰๊ฒฝ๋กœ

[[ICN, SFO], [ICN, ATL], [SFO, ATL], [ATL, ICN], [ATL,SFO]] [ICN, ATL, ICN, SFO, ATL, SFO]

programmers.co.kr

 

๋ฌธ์ œ ํ’€์ด

 ์ฒ˜์Œ์— ์ƒ๊ฐํ•  ๋•Œ๋Š” ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , ๊ฐ ๊ฒฝ๋กœ๋ฅผ ๋ฐฉ๋ฌธํ•ด๋ณด๊ณ  ์•ŒํŒŒ๋ฒณ ์ˆœ์— ๋”ฐ๋ผ ๊ฐ€์žฅ ์•ž์˜ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋ ค๊ณ  ํ•˜์˜€๋‹ค. ํ•˜์ง€๋งŒ ์ฃผ์–ด์ง„ ํ‹ฐ์ผ“์˜ ๋ฐฉ๋ฌธ ๊ฒฝ๋กœ์— ๋”ฐ๋ผ, ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ์ถœ๋ฐœ์ง€์—์„œ ๋ฐฉ๋ฌธ๊ฐ€๋Šฅํ•œ ๊ฒฝ๋กœ๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ฐฑํŠธ๋ž™ํ‚น์„ ํ•˜์ง€ ์•Š๊ณ  ๋ฌธ์ œ๋ฅผ ํ’€ ์ˆ˜ ์žˆ๋‹ค.

 

{
    'ICN': ['ATL', 'SFO'], 
    'SFO': ['ATL'], 
    'ATL': ['ICN', 'SFO']
}

 

 ์˜ˆ์ œ #2์˜ ๊ฒฝ์šฐ, ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ํ†ตํ•ด ๋„์ฐฉ์ง€์˜ ์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๋ฉด ์œ„์™€ ๊ฐ™์ด ์ •๋ ฌํ•  ์ˆ˜ ์žˆ๋‹ค. ์ •๋ ฌ๋œ ์ƒํƒœ์˜ ๋”•์…”๋„ˆ๋ฆฌ๋Š” `INC`๋ฅผ ์‹œ์ž‘ํ•˜์œผ๋กœ ๋”•์…”๋„ˆ๋ฆฌ์˜ value์˜ ์ฒซ๋ฒˆ์งธ์ธ `ATL`๋ถ€ํ„ฐ ๋ฐฉ๋ฌธํ•˜๋ฉด `ICN - ATL - ICN - SFO - ATL - SFO` ์ˆœ์œผ๋กœ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

from collections import defaultdict, deque


def solution(tickets):
    stack, answer = ["ICN"], deque()

    paths = defaultdict(list)
    for departure, arrival in tickets:
        # ์‚ฌ์ „์ˆœ์œผ๋กœ ๋ฐฉ๋ฌธํ•˜๊ธฐ ์œ„ํ•ด, ์ถ”๊ฐ€ํ•  ๋•Œ ์ •๋ ฌ.
        paths[departure] = sorted(paths[departure] + [arrival])

    while stack:
        cur_loc = stack[-1]
        
        # ํ˜„์žฌ ์ถœ๋ฐœ์ง€๋กœ ๋ถ€ํ„ฐ, ๋ฐฉ๋ฌธ๊ฐ€๋Šฅํ•œ ๊ฒฝ๋กœ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ.
        if cur_loc in paths and paths[cur_loc]:
            stack.append(paths[cur_loc][0])
            paths[cur_loc].pop(0)
            continue
            
        # ์ถœ๋ฐœ์ง€๋กœ ๋ถ€ํ„ฐ ๋ฐฉ๋ฌธ ๊ฐ€๋Šฅํ•œ ๊ฒฝ๋กœ๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ.
        answer.appendleft(stack.pop())

    return answer

 

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