smj007

Cheapest flight within K stops

Aug 21st, 2025
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. class Solution:
  2.     def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
  3.  
  4.         graph = defaultdict(list)
  5.         for source, destination, price in flights:
  6.             graph[source].append((destination, price))
  7.  
  8.  
  9.         # pruning strategy
  10.         # track min paths to reach a particular stop
  11.         # avoid travelling down that path if the min
  12.         # is already achieved
  13.         stops = [float("inf")]*n
  14.  
  15.         # PQ: (cost, current_city, num_stops)
  16.         pq = [(0, src, 0)]
  17.  
  18.         while pq:
  19.             cost, current_city, num_stops = heapq.heappop(pq)
  20.  
  21.             # prune conditions
  22.             # we have already found a path to this city with fewer stops
  23.             # or max_total_flights (k+1) exceeded
  24.             if num_stops >= stops[current_city] or num_stops > k + 1:
  25.                 continue
  26.  
  27.             # set min here
  28.             stops[current_city] = num_stops
  29.  
  30.             # end condition
  31.             if current_city == dst:
  32.                 return cost
  33.  
  34.             for nbr, price in graph[current_city]:
  35.                 heapq.heappush(pq, (cost + price, nbr, num_stops + 1))
  36.  
  37.         return -1
  38.  
  39.  
Advertisement
Add Comment
Please, Sign In to add comment