150強訪談簡單

網路延遲時間

「網路延遲時間」問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個由 n 個節點組成的網絡,標記為 1 到 n。您還會獲得時間,即有向邊 times[i] = [ui, vi, wi] 形式的行進時間列表,其中 ui 是來源節點,vi 是目標節點,wi 是訊號從來源行進到目標所需的時間。

我們將從給定節點 k 發送訊號。返回所有n個節點接收到訊號所需的最短時間。如果不可能所有n個節點都收到訊號,則回傳-1。

寫一個函數 networkDelayTime(times: List[List[int]], n: int, k: int) -> int

約束條件
  • 1 <= k <= n <= 100
  • 1 <= len(times) <= 6000
  • times[i].length == 3
  • 1 <= ui, vi <= n
  • ui != vi
  • 0 <= wi <= 100
  • All the pairs (ui, vi) are unique

範例

Example 1
Input
times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output
2
Explanation

The signal starts at node 2. It reaches 1 and 3 in 1 unit of time, and 4 in 2 units of time.

Example 2
Input
times = [[1,2,1]], n = 2, k = 1
Output
1
Explanation

Signal reaches node 2 from node 1 in 1 unit of time.

Example 3
Input
times = [[1,2,1]], n = 2, k = 2
Output
-1
Explanation

Signal starts at node 2, but there is no path from node 2 to node 1. So node 1 never receives it.

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

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