150强访谈简单

K 站内最便宜的航班

“K 经停内最便宜的航班”问题的详细指南和 Python 实施。

问题陈述

简单

有 n 个城市由一定数量的航班连接。给定一个航班数组,其中 Flights[i] = [from_i, to_i, Price_i] 表示有从城市 from_i 到城市 to_i 的航班,成本为 Price_i。

还给你三个整数 src、dst 和 k,返回从 src 到 dst 的最便宜价格,最多有 k 个停靠点。如果没有这样的路由,则返回-1。

编写一个函数 findCheapestPrice(n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int

约束条件
  • 1 <= n <= 100
  • 0 <= len(flights) <= (n * (n - 1) / 2)
  • flights[i].length == 3
  • 0 <= from_i, to_i < n
  • 1 <= price_i <= 10^4
  • 0 <= src, dst < n
  • src != dst
  • 0 <= k < n

示例

Example 1
Input
n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
Output
700
Explanation

The cheapest path from city 0 to city 3 with at most 1 stop is 0 -> 1 -> 3 with cost 100 + 600 = 700.

Example 2
Input
n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output
200
Explanation

Cheapest path is 0 -> 1 -> 2 with cost 200, which has exactly 1 stop.

Need a Hint?
考虑使用高级图特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。