标签:src 787 int 中转 dst flights type Leetcode 500
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
标签:src,787,int,中转,dst,flights,type,Leetcode,500 来源: https://blog.csdn.net/m0_46753549/article/details/119900825
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。