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

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค / Python] ์—ฌํ–‰๊ฒฝ๋กœ

meeeeejin 2021. 4. 1. 00:19

๋ฌธ์ œ ๋งํฌ: programmers.co.kr/learn/courses/30/lessons/43164

 

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

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

programmers.co.kr

 

 

๋ฌธ์ œ ์„ค๋ช…

DFS๋ฅผ ์ด์šฉํ•ด ๋ชจ๋“  ํ‹ฐ์ผ“์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ๋กœ๋ฅผ ํƒ์ƒ‰ํ•ฉ๋‹ˆ๋‹ค. ์ด๋•Œ DFS์˜ ์ˆœ์„œ๋ฅผ ์Šคํƒ์— ์ €์žฅํ–ˆ๋‹ค๊ฐ€ ์Šคํƒ top์—์„œ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ๋กœ๊ฐ€ ์—†์„ ๊ฒฝ์šฐ์— answer์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ๋กœ๊ฐ€ ์—†๋‹ค๋Š” ๊ฒƒ์€ ๊ทธ ๊ณตํ•ญ์ด ์ œ์ผ ๋งˆ์ง€๋ง‰ ๋ฐฉ๋ฌธ์ง€๋ผ๋Š” ์˜๋ฏธ์ž…๋‹ˆ๋‹ค. ์ฆ‰, answer์—๋Š” ๊ณตํ•ญ์„ ๋ฐฉ๋ฌธํ•˜๋Š” ์ˆœ์„œ๊ฐ€ ๊ฑฐ๊พธ๋กœ ์ €์žฅ๋˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ๋งˆ์ง€๋ง‰์— answer์„ ๋’ค์ง‘์–ด์„œ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค. 

 

  1. ํ‹ฐ์ผ“์˜ ์ •๋ณด(start, end)๋ฅผ ๋”•์…”๋„ˆ๋ฆฌ routes์— ์ €์žฅ
  2. routes๋Š” start๋ฅผ key๋กœ ํ•˜๊ณ , end๋ฅผ ๋ฆฌ์ŠคํŠธ์˜ ์›์†Œ๋กœ ๊ฐ–๋Š” ๋”•์…”๋„ˆ๋ฆฌ
  3. DFS์—์„œ pop์„ ์ด์šฉํ•ด์„œ ์•ŒํŒŒ๋ฒณ ์ˆœ์„œ๋Œ€๋กœ ํ‹ฐ์ผ“์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ๊ฐ key์— ๋Œ€ํ•ด value ๋ฆฌ์ŠคํŠธ๋ฅผ ์•ŒํŒŒ๋ฒณ ์—ญ์ˆœ์œผ๋กœ ์ •๋ ฌ
  4. ์Šคํƒ์— ์ถœ๋ฐœ ์ง€์  "ICN"์„ ์‚ฝ์ž…
  5. ์Šคํƒ top์„ start๋กœ ํ•˜๋Š” ํ‹ฐ์ผ“์ด ๋‚จ์•„์žˆ์ง€ ์•Š์€ ๊ฒฝ์šฐ top์„ ์Šคํƒ์—์„œ ๊บผ๋‚ด์„œ answer์— ์‚ฝ์ž…
  6. ์Šคํƒ top์„ start๋กœ ํ•˜๋Š” ํ‹ฐ์ผ“์ด ๋‚จ์•„์žˆ๋Š” ๊ฒฝ์šฐ ํ•ด๋‹น ํ‹ฐ์ผ“์„ routes์—์„œ ๊บผ๋‚ด๊ณ  end๋ฅผ ์Šคํƒ์— ์‚ฝ์ž…
  7. ์Šคํƒ์ด ๋นŒ ๋•Œ๊นŒ์ง€ 5~6๋ฒˆ ๋ฐ˜๋ณต ์ˆ˜ํ–‰
  8. answer์„ ์—ญ์ˆœ์œผ๋กœ ๋ฐ˜ํ™˜

 

 

 

์†Œ์Šค์ฝ”๋“œ

def solution(tickets):
    answer = []
    routes = dict() # ํ‹ฐ์ผ“ ์ •๋ณด๋ฅผ ์ €์žฅํ•˜๋Š” ๋”•์…”๋„ˆ๋ฆฌ

    for (start, end) in tickets:
        if start in routes:
            routes[start].append(end)
        else:
            routes[start] = [end]
    # ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ณตํ•ญ์„ ์•ŒํŒŒ๋ฒณ ์—ญ์ˆœ์œผ๋กœ ์ •๋ ฌ
    for r in routes.keys():
        routes[r].sort(reverse = True)

    st = ["ICN"]
    while st:
        top = st[-1]
        # ์Šคํƒ top์„ start๋กœ ํ•˜๋Š” ํ‹ฐ์ผ“์ด ์—†๋Š” ๊ฒฝ์šฐ
        if (top not in routes) or (not routes[top]):
            answer.append(st.pop())   # top์„ ์Šคํƒ์—์„œ ๊บผ๋‚ด์„œ answer์— ์ €์žฅ
        # ์Šคํƒ top์„ start๋กœ ํ•˜๋Š” ํ‹ฐ์ผ“์ด ์žˆ๋Š” ๊ฒฝ์šฐ
        else:
            st.append(routes[top].pop())

    return answer[::-1]

 

 

 

 

728x90