LLancelot / LeetCode

✍️ My LeetCode solutions, ideas and templates sharing. (我的LeetCode题解,思路以及各专题的解题模板分享。分专题归纳,见tag)
https://leetcode.com/lancelot_/
163 stars 40 forks source link

787. Cheapest Flights Within K Stops #22

Open LLancelot opened 4 years ago

LLancelot commented 4 years ago

https://leetcode.com/problems/cheapest-flights-within-k-stops/

Example 1: Input: n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]] src = 0, dst = 2, k = 1 Output: 200 Explanation: The graph looks like this:

image

代码

LLancelot commented 3 years ago
from heapq import *
class Solution(object):
    def findCheapestPrice(self, n, flights, src, dst, total_stops):

        dic = defaultdict(list)
        for start, end, price in flights:
            dic[start].append((end, price))

        stop = 0
        heap = [(0, -1, src)]
        while heap:
            cur_price, cur_stop, cur_city = heappop(heap)
            if cur_city == dst:
                return cur_price

            if cur_stop < total_stops:
                for nb, nb_price in dic[cur_city]:
                    heappush(heap, (cur_price + nb_price, cur_stop + 1, nb))
        return -1