Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
- All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
- For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
- You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
- """
- from collections import defaultdict
- import heapq
- class Solution:
- def findItinerary(self, tickets: List[List[str]]) -> List[str]:
- # Create an adjacency list with a priority queue (min-heap) for each airport
- graph = defaultdict(list)
- for src, dest in tickets:
- heapq.heappush(graph[src], dest)
- # Result itinerary list (to be reversed at the end)
- itinerary = []
- # Depth-First Search function using stack
- def dfs(airport):
- # Use the heap to get the lexicographically smallest destination
- while graph[airport]:
- next_airport = heapq.heappop(graph[airport])
- dfs(next_airport)
- itinerary.append(airport)
- # Start DFS from 'JFK'
- dfs('JFK')
- # The itinerary is constructed in reverse, so reverse it back
- return itinerary[::-1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement