【Leetcode每日一题】787. K 站中转内最便宜的航班

2021/8/24 23:36:03

本文主要是介绍【Leetcode每日一题】787. K 站中转内最便宜的航班,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

787. K 站中转内最便宜的航班

  • 题目
  • 示例
  • 关键思路
  • 代码实现
  • 运行结果
  • 链接


题目

有 n 个城市通过一些航班连接。给你一个数组 flights ,其中 flights[i] = [from(i), to(i), price(i)] ,表示该航班都从城市 fromi 开始,以价格 price(i) 抵达 to(i)。

现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到出一条最多经过 k 站中转的路线,使得从 src 到 dst 的 价格最便宜 ,并返回该价格。 如果不存在这样的路线,则输出 -1。

示例

示例1

输入:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
输出: 200
解释: 从城市 0 到城市 2 在 1 站中转以内的最便宜价格是 200

示例2

输入:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
输出: 500
解释: 从城市 0 到城市 2 在 0 站中转以内的最便宜价格是 500


关键思路

本质为求最短路径,这里使用到A*寻路算法。

代码实现

class Solution(object):
    def findCheapestPrice(self, n, flights, src, dst, k):
        """
        :type n: int  number of cities
        :type flights: List[List[int]]
        :type src: int
        :type dst: int
        :type k: int  max sites
        :rtype: int  min price or -1
        """

        # A-star
        cur = src
        open_list = [ [float("inf"), -1 ] for i in range(n)]
        open_list[0][0] = 0

        while cur!=dst:
            for flight in flights:
                if cur == flight[0]:  # match
                    if open_list[cur][0]+flight[2] <= open_list[flight[1]][0]:  # compare
                        if flight[1] <= dst and open_list[flight[1]][1] < k: # compare the number
                            open_list[flight[1]][0] = open_list[cur][0]+flight[2]  # update
                            open_list[flight[1]][1] += 1
            cur = cur+1
        
        return open_list[dst][0] if open_list[dst][0] != float("inf") else -1
    

if __name__ == "__main__":
    n = input()
    edges = input()
    src = input()
    dst = input()
    k = input()
    obj = Solution()
    result = obj.findCheapestPrice(n, edges, src, dst, k)
    print(result)

运行结果

200
500

链接

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



这篇关于【Leetcode每日一题】787. K 站中转内最便宜的航班的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程