Problem Description
Given an undirected weighted graph with n nodes, you start at node 0 and want to determine the minimum time required to reach every node. Each edge is represented as [u, v, length] where length is the travel time between nodes u and v. Additionally, each node i has a disappearance time given by disappear[i]. If you arrive at a node at a time greater than or equal to its disappearance time, you cannot visit it. Return an answer array where answer[i] is the minimum time to reach node i before it disappears or -1 if unreachable.
Key Insights
- This is a shortest path problem with an extra constraint on the arrival time at nodes.
- Use Dijkstra's algorithm to find the minimum travel time from the source node.
- At each step, only relax the edge if the arrival time at the destination is strictly less than its disappearance time.
- The graph may have multiple edges and can be disconnected.
Space and Time Complexity
Time Complexity: O((E + V) log V) where E is the number of edges and V is the number of nodes. Space Complexity: O(V + E) for the graph representation and O(V) for the distance storage and heap.
Solution
We solve the problem using Dijkstra’s algorithm with a min-heap (priority queue). The modifications compared to the standard Dijkstra are:
- Initialize the distance for node 0 as 0 and for all other nodes as infinity.
- Use a min-heap which stores pairs of (time, node).
- While processing each node from the heap, check if the current time is strictly less than the node’s disappearance time. If not, skip relaxing its edges.
- For each adjacent node, if the new accumulated time is less than both its recorded distance and its disappearance time, update the distance and push it onto the heap.
- Finally, convert any unreachable nodes (still infinity) to -1 in the result answer.
This method guarantees that we only consider valid arrival times (i.e., before the node disappears) and computes the minimum travel time accordingly.