787. Cheapest Flights Within K Stops
solution
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
graph = collections.defaultdict(dict)
pq = [(0, src, 0)]
for u, v, w in flights:
graph[u][v] = w
while pq:
total, src, stops = heapq.heappop(pq)
if src == dst:
return total
if stops > k:
continue
for dest, cost in graph[src].items():
heapq.heappush(pq, (total + cost, dest, stops + 1))
return -1Last updated