[LeetCode] 332. Reconstruct Itinerary (Python)
- Reference
graph
- λ°±μ€: List
- LeetCode: defaultdict(list)
SolutionPermalink
import collections
from typing import List
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
answer = []
graph = collections.defaultdict(list)
for x, y in sorted(tickets):
graph[x].append(y)
def dfs(x: str):
# μ¬κ·λ‘ λ€ λ°©λ¬Ένλ€λ λ»
while graph[x]:
# μ΄ν μ λ°©λ¬Έ -> κ°μ₯ 첫 λ²μ§Έ κ°
dfs(graph[x].pop(0))
answer.append(x)
dfs('JFK')
answer.reverse()
return answer
Leave a comment