파이썬 알고리즘 인터뷰 문제 41번(리트코드 787번) Cheapest Flights Within K Stops
https://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 from_, to, price in flights:
graph[from_].append((to, price))
prices = collections.defaultdict(list)
Q = [(0, 0, src)] # price, stops, city
while Q:
price, stops, city = heapq.heappop(Q)
#print(price, stops, city, prices)
#print(Q)
if stops <= k + 1:
prices[city].append([price, stops])
for nei, delta_price in graph[city]:
heapq.heappush(Q, (price + delta_price, stops + 1, nei))
#print(prices)
if dst in prices:
return min(price[0] for price in prices[dst] if price[1] <= k + 1)
return -1
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
graph = collections.defaultdict(list)
weight = [(float('inf'), K)] * n
# 그래프 인접 리스트 구성
for u, v, w in flights:
graph[u].append((v, w))
# 큐 변수: [(가격, 정점, 남은 가능 경유지 수)]
Q = [(0, src, K)]
# 우선 순위 큐 최소값 기준으로 도착점까지 최소 비용 판별
while Q:
price, node, k = heapq.heappop(Q)
if node == dst:
return price
if k >= 0:
for v, w in graph[node]:
alt = price + w
if alt < weight[v][0] or k-1 >= weight[v][1]:
weight[v] = (alt, k-1)
heapq.heappush(Q, (alt, v, k - 1))
return -1