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

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