[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/python] ๊นŠ์ด/๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰(DFS/BFS) : ์—ฌํ–‰๊ฒฝ๋กœ

2021. 4. 11. 23:03

๋ฌธ์ œ ์„ค๋ช…

์ฃผ์–ด์ง„ ํ•ญ๊ณต๊ถŒ์„ ๋ชจ๋‘ ์ด์šฉํ•˜์—ฌ ์—ฌํ–‰๊ฒฝ๋กœ๋ฅผ ์งœ๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ํ•ญ์ƒ "ICN" ๊ณตํ•ญ์—์„œ ์ถœ๋ฐœํ•ฉ๋‹ˆ๋‹ค.

ํ•ญ๊ณต๊ถŒ ์ •๋ณด๊ฐ€ ๋‹ด๊ธด 2์ฐจ์› ๋ฐฐ์—ด tickets๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ๋ฐฉ๋ฌธํ•˜๋Š” ๊ณตํ•ญ ๊ฒฝ๋กœ๋ฅผ ๋ฐฐ์—ด์— ๋‹ด์•„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

 

์ œํ•œ์‚ฌํ•ญ

  • ๋ชจ๋“  ๊ณตํ•ญ์€ ์•ŒํŒŒ๋ฒณ ๋Œ€๋ฌธ์ž 3๊ธ€์ž๋กœ ์ด๋ฃจ์–ด์ง‘๋‹ˆ๋‹ค.
  • ์ฃผ์–ด์ง„ ๊ณตํ•ญ ์ˆ˜๋Š” 3๊ฐœ ์ด์ƒ 10,000๊ฐœ ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • tickets์˜ ๊ฐ ํ–‰ [a, b]๋Š” a ๊ณตํ•ญ์—์„œ b ๊ณตํ•ญ์œผ๋กœ ๊ฐ€๋Š” ํ•ญ๊ณต๊ถŒ์ด ์žˆ๋‹ค๋Š” ์˜๋ฏธ์ž…๋‹ˆ๋‹ค.
  • ์ฃผ์–ด์ง„ ํ•ญ๊ณต๊ถŒ์€ ๋ชจ๋‘ ์‚ฌ์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
  • ๋งŒ์ผ ๊ฐ€๋Šฅํ•œ ๊ฒฝ๋กœ๊ฐ€ 2๊ฐœ ์ด์ƒ์ผ ๊ฒฝ์šฐ ์•ŒํŒŒ๋ฒณ ์ˆœ์„œ๊ฐ€ ์•ž์„œ๋Š” ๊ฒฝ๋กœ๋ฅผ return ํ•ฉ๋‹ˆ๋‹ค.
  • ๋ชจ๋“  ๋„์‹œ๋ฅผ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ๋Š” ์ฃผ์–ด์ง€์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

 

์ •๋‹ต

def solution(tickets):

    tickets.sort(reverse=True)
    graph = dict()
    for t in tickets:
        if t[0] not in graph:
            graph[t[0]] = [t[1]]
        else:
            graph[t[0]].append(t[1])
   
    stack = ["ICN"]
    visited = []

    while stack:
        n = stack[-1]
        if n not in graph or len(graph[n]) == 0:
            visited.append(stack.pop())
        else:
            stack.append(graph[n][-1])
            graph[n] = graph[n][:-1]

    return visited[::-1]

    tickets.sort(reverse=True)
    graph = dict()
    for t in tickets:
        if t[0] not in graph:
            graph[t[0]] = [t[1]]
        else:
            graph[t[0]].append(t[1])

tickets๋ฅผ ์—ญ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ ํ›„ ๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ์˜ graph์— 0๋ฒˆ์งธ ์ธ๋ฑ์Šค๋Š” key๋กœ 1๋ฒˆ์งธ ์ธ๋ฑ์Šค๋Š” value๋กœ ์ €์žฅํ•œ๋‹ค.

tickets๋ฅผ ์—ญ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ ํ›„ ์ €์žฅํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— value์—๋Š” ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋˜์–ด ์žˆ์„ ๊ฒƒ์ด๋‹ค.

 

    stack = ["ICN"]
    visited = []

    while stack:
        n = stack[-1]
        if n not in graph or len(graph[n]) == 0:
            visited.append(stack.pop())
        else:
            stack.append(graph[n][-1])
            graph[n] = graph[n][:-1]

    return visited[::-1]

์šฐ์„  stack์— ์ถœ๋ฐœ์ง€์ธ ICN์„ ์ €์žฅํ•œ ํ›„ stack์ด ๋น„์–ด์žˆ์ง€ ์•Š์„๋™์•ˆ ๋ฐ˜๋ณตํ•œ๋‹ค.

n์—๋Š” stack์˜ ๋งˆ์ง€๋ง‰ ๊ฐ’์„ ์ €์žฅํ•ด๋†“๊ณ 

graph[n]์ด ์• ์ดˆ์— ์—†๊ฑฐ๋‚˜ ๋น„์–ด์žˆ์„ ๊ฒฝ์šฐ, ๋งˆ์ง€๋ง‰ ๋„์ฐฉ์ง€๋ผ๋Š” ๋œป์ด๋ฏ€๋กœ

visited์— stack.pop()์ธ n๊ฐ’์„ ์ €์žฅํ•œ๋‹ค.

 

visited์— ๋งˆ์ง€๋ง‰ ๋„์ฐฉ์ง€๋ฅผ ์ €์žฅํ•˜๋Š” ์ด์œ ๋Š” ๋งˆ์ง€๋ง‰์— visited๋ฅผ ์—ญ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•˜๋ฏ€๋กœ

๋ฐฉ๋ฌธํ•˜๋Š” ๊ณตํ•ญ ๊ฒฝ๋กœ๋ฅผ ์—ญ์ˆœ์œผ๋กœ ์ €์žฅํ•ด๋‘์–ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 

๋‹ค์Œ์œผ๋กœ ๊ฐˆ ๊ฒฝ๋กœ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ, stack์— ๋‹ค์Œ ๊ฒฝ๋กœ์ธ graph[n][-1]์„ ์ถ”๊ฐ€ํ•˜๊ณ 

graph[n]์—๋Š” graph[n][-1]์„ ๋บ€ graph[n][::-1]์„ ์ €์žฅํ•œ๋‹ค.

728x90

BELATED ARTICLES

more