Leetcode 3604. Minimum Time to Reach Destination in Directed Graph
- Leetcode 3604. Minimum Time to Reach Destination in Directed Graph
- 1. 解题思路
- 2. 代码实现
- 题目链接:3604. Minimum Time to Reach Destination in Directed Graph
1. 解题思路
这一题思路上就是一个广度优先遍历,我们不断考察当前时间点以及位置的情况下,下一个点可行的位置,然后考察最近的时间点能够到达的位置,遍历全部可能性直至达到目标位置即可。
2. 代码实现
给出python代码实现如下:
class Solution:def minTime(self, n: int, edges: List[List[int]]) -> int:graph = defaultdict(list)for u, v, st, ed in edges:graph[u].append((v, st, ed))q = [(0, 0)]seen = set()while q:t, u = heapq.heappop(q)if u == n-1:return tif u in seen:continueseen.add(u)for v, st, ed in graph[u]:if t > ed or v in seen:continueheappush(q, (max(t+1, st+1), v))return -1
提交代码评测得到:耗时234ms,占用内存72.14MB。