반응형
leetcode.com/problems/cheapest-flights-within-k-stops/
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
graph = collections.defaultdict(list)
for u,v,w in flights:
graph[u].append([v,w])
# stops, cost
result = []
# cost, node, stops
Q = [[0,src,-1]]
while Q:
cost, node, stops = heapq.heappop(Q)
if node == dst :
return cost
if stops < K:
for v,w in graph[node]:
alt = cost + w
heapq.heappush(Q, [alt,v,stops+1])
return -1
댓글