Minimum Time to Reach Destination in Directed Graph Problem
Description
LeetCode Problem 3604.
You are given an integer n and a directed graph with n nodes labeled from 0 to n - 1. This is represented by a 2D array edges, where edges[i] = [u_i, v_i, start_i, end_i] indicates an edge from node u_i to v_i that can only be used at any integer time t such that start_i <= t <= end_i.
You start at node 0 at time 0.
In one unit of time, you can either:
- Wait at your current node without moving, or
- Travel along an outgoing edge from your current node if the current time
tsatisfiesstart_i <= t <= end_i.
Return the minimum time required to reach node n - 1. If it is impossible, return -1.
Example 1:
Input: n = 3, edges = [[0,1,0,1],[1,2,2,5]]
Output: 3
Explanation:

The optimal path is:
- At time t = 0, take the edge (0 → 1) which is available from 0 to 1. You arrive at node 1 at time t = 1, then wait until t = 2.
- At time t = 2, take the edge (1 → 2) which is available from 2 to 5. You arrive at node 2 at time 3.
Hence, the minimum time to reach node 2 is 3.
Example 2:
Input: n = 4, edges = [[0,1,0,3],[1,3,7,8],[0,2,1,5],[2,3,4,7]]
Output: 5
Explanation:

The optimal path is:
- Wait at node 0 until time t = 1, then take the edge (0 → 2) which is available from 1 to 5. You arrive at node 2 at t = 2.
- Wait at node 2 until time t = 4, then take the edge (2 → 3) which is available from 4 to 7. You arrive at node 3 at t = 5.
Hence, the minimum time to reach node 3 is 5.
Example 3:
Input: n = 3, edges = [[1,0,1,3],[1,2,3,5]]
Output: -1
Explanation:

- Since there is no outgoing edge from node 0, it is impossible to reach node 2. Hence, the output is -1.
Constraints:
1 <= n <= 10^50 <= edges.length <= 10^5edges[i] == [u_i, v_i, start_i, end_i]0 <= u_i, v_i <= n - 1u_i != v_i0 <= start_i <= end_i <= 10^9
Solution
Approach: Dijkstra on Arrival Time
Arriving earlier is never worse, because you can always wait. So keep the earliest known arrival time dist[v] for every node and run Dijkstra with a heap on that time.
From node u reached at time t, an edge (u, v, start, end) can be taken at time go = max(t, start) (wait until it opens), as long as go <= end. You then arrive at v at time go + 1. Relax dist[v] with that value. The answer is dist[n - 1], or -1 if it is never reached.
Complexity: O((n + e) log e) time and O(n + e) extra space.
import heapq
class Solution:
def minTime(self, n: int, edges: List[List[int]]) -> int:
g = [[] for _ in range(n)]
for u, v, s, e in edges:
g[u].append((v, s, e))
INF = float("inf")
dist = [INF] * n
dist[0] = 0
pq = [(0, 0)]
while pq:
t, u = heapq.heappop(pq)
if t > dist[u]:
continue
if u == n - 1:
return t
for v, s, e in g[u]:
go = max(t, s)
if go <= e and go + 1 < dist[v]:
dist[v] = go + 1
heapq.heappush(pq, (go + 1, v))
return -1