1. 问题
有 n 个城市通过 m 个航班连接。每个航班都从城市 u 开始,以价格 w 抵达 v。
现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到从 src 到 dst 最多经过 k 站中转的最便宜的价格。 如果没有这样的路线,则输出 -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,如图中红色所示。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cheapest-flights-within-k-stops
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题思路
BFS常规题,小技巧是用dict记录航班信息,如果每个城市都遍历航班List会很耗时。此外,用visited记录遍历到某城市所需要的价格,如果有新的线路到达该城市花费更少,会把线路放入队列,再次从该城市进行遍历。
from collections import deque
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
# BFS
queue = deque()
# start, k, price
queue.append((src, 0, 0))
# start,price
visited = [-1 for _ in range(100)]
visited[src] = 0
res = -1
f_dict = {}
for item in flights:
if item[0] not in f_dict.keys():
f_dict[item[0]] = []
f_dict[item[0]].append([item[1],item[2]])
else:
f_dict[item[0]].append([item[1],item[2]])
while len(queue) > 0:
city, mid, price = queue.popleft()
if mid > K:
continue
if city in f_dict.keys():
for item in f_dict[city]:
n_city = item[0]
n_price = price + item[1]
if n_city == dst:
if res == -1:
res = n_price
else:
res = min(res,n_price)
if (visited[n_city] == -1) or (visited[n_city] > n_price):
visited[n_city] = n_price
queue.append((n_city,mid+1,n_price))
return res