Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
- graph = defaultdict(list)
- for source, destination, price in flights:
- graph[source].append((destination, price))
- # pruning strategy
- # track min paths to reach a particular stop
- # avoid travelling down that path if the min
- # is already achieved
- stops = [float("inf")]*n
- # PQ: (cost, current_city, num_stops)
- pq = [(0, src, 0)]
- while pq:
- cost, current_city, num_stops = heapq.heappop(pq)
- # prune conditions
- # we have already found a path to this city with fewer stops
- # or max_total_flights (k+1) exceeded
- if num_stops >= stops[current_city] or num_stops > k + 1:
- continue
- # set min here
- stops[current_city] = num_stops
- # end condition
- if current_city == dst:
- return cost
- for nbr, price in graph[current_city]:
- heapq.heappush(pq, (cost + price, nbr, num_stops + 1))
- return -1
Advertisement
Add Comment
Please, Sign In to add comment