LeetCode 题解工作台
有向图中到达终点的最少时间
给你一个整数 n 和一个 有向 图,图中有 n 个节点,编号从 0 到 n - 1 。图由一个二维数组 edges 表示,其中 edges[i] = [u i , v i , start i , end i ] 表示从节点 u i 到 v i 的一条边,该边 只能 在满足 start i i 的整数…
3
题型
0
代码语言
3
相关题
当前训练重点
中等 · 堆
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 堆 题型思路
题目描述
给你一个整数 n 和一个 有向 图,图中有 n 个节点,编号从 0 到 n - 1。图由一个二维数组 edges 表示,其中 edges[i] = [ui, vi, starti, endi] 表示从节点 ui 到 vi 的一条边,该边 只能 在满足 starti <= t <= endi 的整数时间 t 使用。
你在时间 0 从在节点 0 出发。
在一个时间单位内,你可以:
- 停留在当前节点不动,或者
- 如果当前时间
t满足starti <= t <= endi,则从当前节点沿着出边的方向移动。
返回到达节点 n - 1 所需的 最小 时间。如果不可能,返回 -1。
示例 1:
输入:n = 3, edges = [[0,1,0,1],[1,2,2,5]]
输出:3
解释:

最佳路径为:
- 在时间
t = 0,走边(0 → 1),该边在 0 到 1 的时间段内可用。你在时间t = 1到达节点 1,然后等待直到t = 2。 - 在时间
t =,走边2(1 → 2),该边在 2 到 5 的时间段内可用。你在时间 3 到达节点 2。
因此,到达节点 2 的最小时间是 3。
示例 2:
输入: n = 4, edges = [[0,1,0,3],[1,3,7,8],[0,2,1,5],[2,3,4,7]]
输出: 5
解释:

最佳路径为:
- 在节点 0 等待直到时间
t = 1,然后走边(0 → 2),该边在 1 到 5 的时间段内可用。你在t = 2到达节点 2。 - 在节点 2 等待直到时间
t = 4,然后走边(2 → 3),该边在 4 到 7 的时间段内可用。你在t = 5到达节点 3。
因此,到达节点 3 的最小时间是 5。
示例 3:
输入: n = 3, edges = [[1,0,1,3],[1,2,3,5]]
输出: -1
解释:

- 由于节点 0 没有出边,因此无法到达节点 2。输出为 -1。
提示:
1 <= n <= 1050 <= edges.length <= 105edges[i] == [ui, vi, starti, endi]0 <= ui, vi <= n - 1ui != vi0 <= starti <= endi <= 109
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the number of edges and the number of states to explore (node-time pairs). For this problem, the complexity is roughly `O(E log N)` due to the priority queue operations, where `E` is the number of edges and `N` is the number of nodes. Space complexity is `O(E + N)` for storing the graph and the state information in the priority queue. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate's ability to adapt Dijkstra's algorithm to a time-dependent graph is crucial.
- question_mark
Look for understanding of how to manage a priority queue for time-sensitive decisions.
- question_mark
The ability to correctly handle edge availability based on time constraints should be checked.
常见陷阱
外企场景- error
Not accounting for edge availability based on the time constraint could lead to incorrect results.
- error
Failing to manage the priority queue properly might result in inefficient solutions.
- error
Incorrectly assuming that waiting at a node does not affect the overall time could lead to failures in edge cases.
进阶变体
外企场景- arrow_right_alt
The problem could be extended by introducing cycles in the graph, requiring careful handling of revisited nodes.
- arrow_right_alt
An alternate version might add random edge delays or multiple time windows per edge.
- arrow_right_alt
A variant could involve finding the longest time instead of the shortest, which changes the algorithm's focus.