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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。