Minimum Time to Visit Disappearing Nodes - Problem
You're navigating through a time-sensitive network where nodes can vanish at specific moments! Given an undirected graph with n nodes, you need to find the shortest path from node 0 to every other node before they disappear.
The graph is described by:
- edges[i] = [ui, vi, lengthi]: An edge between nodes ui and vi with traversal time of lengthi units
- disappear[i]: The time when node i vanishes from the graph (you cannot visit it after this time)
Important: The graph might be disconnected and can contain multiple edges between the same pair of nodes.
Goal: Return an array where answer[i] is the minimum time to reach node i from node 0. If node i is unreachable or disappears before you can reach it, return -1.
Input & Output
example_1.py โ Basic Connected Graph
$
Input:
n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5]
โบ
Output:
[0, -1, 4]
๐ก Note:
Node 0 is the starting point (time 0). Node 1 disappears at time 1, but the shortest path takes time 2, so it's unreachable (-1). Node 2 can be reached via path 0โ2 in time 4, which is before its disappear time of 5.
example_2.py โ Multiple Paths Available
$
Input:
n = 4, edges = [[0,1,5],[0,2,3],[1,3,2],[2,3,4]], disappear = [10,8,8,10]
โบ
Output:
[0, 5, 3, 7]
๐ก Note:
All nodes are reachable: Node 1 via 0โ1 (time 5), Node 2 via 0โ2 (time 3), Node 3 via 0โ1โ3 (time 7, shorter than 0โ2โ3 which takes time 7).
example_3.py โ Disconnected Graph Edge Case
$
Input:
n = 3, edges = [[0,1,2]], disappear = [10,10,10]
โบ
Output:
[0, 2, -1]
๐ก Note:
Node 2 is completely disconnected from the component containing nodes 0 and 1, so it's unreachable regardless of its disappear time.
Constraints
- 1 โค n โค 5 ร 104
- 0 โค edges.length โค 2 ร 105
- edges[i].length == 3
- 0 โค ui, vi โค n - 1
- 0 โค lengthi โค 104
- disappear.length == n
- 1 โค disappear[i] โค 104
- The graph may contain multiple edges and self-loops
Visualization
Tap to expand
Understanding the Visualization
1
Setup Network
Build the rescue network with weighted paths and closure times for each station
2
Start from HQ
Begin from headquarters (node 0) at time 0, using a priority queue to explore nearest stations first
3
Check Time Constraints
For each path, verify we can reach the destination before its closure time
4
Find Optimal Routes
Use Dijkstra's algorithm to find shortest valid paths to all reachable stations
Key Takeaway
๐ฏ Key Insight: Dijkstra's algorithm naturally finds the shortest paths, and by checking disappear times during edge relaxation, we ensure all returned paths are valid and optimal.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code