Advertisement
hoangreal

Reconstruct Airport Initery

Oct 21st, 2024
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. """
  2. 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.
  3.  
  4. 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.
  5.  
  6. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
  7. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
  8. """
  9.  
  10. from collections import defaultdict
  11. import heapq
  12.  
  13. class Solution:
  14.     def findItinerary(self, tickets: List[List[str]]) -> List[str]:
  15.         # Create an adjacency list with a priority queue (min-heap) for each airport
  16.         graph = defaultdict(list)
  17.         for src, dest in tickets:
  18.             heapq.heappush(graph[src], dest)
  19.        
  20.         # Result itinerary list (to be reversed at the end)
  21.         itinerary = []
  22.        
  23.         # Depth-First Search function using stack
  24.         def dfs(airport):
  25.             # Use the heap to get the lexicographically smallest destination
  26.             while graph[airport]:
  27.                 next_airport = heapq.heappop(graph[airport])
  28.                 dfs(next_airport)
  29.             itinerary.append(airport)
  30.        
  31.         # Start DFS from 'JFK'
  32.         dfs('JFK')
  33.        
  34.         # The itinerary is constructed in reverse, so reverse it back
  35.         return itinerary[::-1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement