LeetCode 787. Cheapest Flights Within K Stops - BFS - Python 3 - for Coding Interviews

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
adj = defaultdict(list)
for f, t, p in flights:
adj[f].append((t, p))

cost = [inf]*n
queue = deque([(src, 0, 0)])
cost[src] = 0
while queue:
node, accum_price, step = queue.popleft()
for neighbor, price in adj[node]:
if step <= k and accum_price+price < cost[neighbor]:
cost[neighbor] = accum_price+price
queue.append((neighbor, cost[neighbor], step+1))
return cost[dst] if cost[dst]<inf else -1

alicecodeland
Автор

Couple questions, suppose we have a direct flight going to a node say cost is 5 and through intermediate nodes say we reach that same node but cost is 7 (note this node I am referring is not the destination node but just another intermediate node) so should we take the cost for this as 5 plus 0s for the extra k steps taken to reach through some other intermediate nodes or do I take the cost to be 7 because at Kathy’s step cost is 7(again note the node I am referring to here is not the final destination node)

hari
welcome to shbcf.ru