There is an undirected graph of n nodes. You are given a 2D array edges, where
edges[i] = [ui, vi, lengthi] describes an edge between node ui and node vi with
a traversal time of lengthi units.
Additionally, you are given an array disappear, where disappear[i] denotes the time
when the node i disappears from the graph and you won't be able to visit it.
Return the array answer, with answer[i] denoting the minimum units of time required to
reach node i from node 0. If node i is unreachable from node 0 then answer[i] is -1.
Example: Emergency Fire Response
Imagine a fire station dispatching emergency response teams to different houses across a city. Roads connecting the locations have different travel times, and some houses may become completely engulfed in flames after a certain time, making them inaccessible.
Determine the earliest time an emergency team can reach each house, ensuring it arrives before that house becomes inaccessible.
Playground: Leetcode 3112
Basic Intuition
-
We need to find the minimum time required to reach every node connected to the source node, provided it is within the accepted threshold.
-
An edge list is not an efficient representation for this problem, as it requires scanning the entire list to identify the neighbours of a particular node. We can convert the edge list into an adjacency list, which allows us to directly access the neighbours of a node.
-
An improvement in one node's shortest path can lead to improvements in other nodes' shortest distances. Therefore, whenever we discover a shorter path to a node, we need to explore its neighbours again using the updated distance. This is the core principle behind Shortest Path Faster algorithm.
Naive Approach: Shortest Path Faster Algorithm
We start from the source node and explore its neighbours. Whenever we find a shorter path to a node, we add it to a queue so that we can explore its neighbours using the updated distances.
Algorithm
1. Covert the input edge list into an adjacency list. Since the graph is undirected,
add each edge in both directions, so that each endpoint (node) is represented as
a neighbour of the other.
2. Create an "answer" array of size "n", initializing the minimum travel time for each
node to Infinity.
3. Set the minimum time of the source node to 0 and add it to the queue.
4. Continue processing until the queue becomes empty.
5. Remove the oldest node from the queue and retrieve its current minimum travel time.
6. Iterate over all outgoing neigbours of the current node along with their corresponding
edge weights.
7. For each neighbour, calculate the minimum travel time required to reach it through the
current node: "newTime = answer[currentNode] + edgeWeight".
8. If "newTime" is smaller than the existing minimum travel time of the neighbour and denotes
not exceed the threshold, update its minimum travel time add the neighbour to the queue.
8. Replace the minimum travel time for all unreachable nodes from Infinity to -1.
9. Return the "answer" array.
Implementation
Time Complexity
The time complexity depends on the the following operations:
-
Initializing the adjacency list: We iterate over all vertices to initialize their adjacency lists, which takes
O(V)time. We then iterate over all edges to populate the adjacency list. Since the graph is undirected, each edge is added to the adjacency lists of both endpoints. This takesO(E)time. Therefore, this takesO(V + E). -
Queue processing: A node can be enqueued and processed multiple times. Whenever we process a node, we explore all its neighbours. In the worst case, every single vertex gets updated and re-queued
(V - 1)times. f every vertex is poppedO(V)times and each pop checks all its outgoing edges, the sum of all edge checks across all vertices equalsO(V * E). ------ Need to explore this more ----- -
Converting unreachable nodes to
-1: We iterate over theanswerarray once to identify unreachable nodes and update their values to-1. Since the array contains(V)elements, this takesO(V).
Hence, the overall time complexity is O(V + E) + O(V * E) + O(V) = O(V * E).
Space Complexity
The space complexity is primarily determined by three data structures:
-
Adjacency list: Each of the
(V)vertices requires an adjacency list. Each of the(E)edges is stored twice because the graph is undirected. This takesO(V + E). -
answerarray: Since the array contains(V)elements, this takesO(V). -
Queue: In the standard SPFA implementation, we maintain an additional
inQueue[]array. Whenever we enqueue a node, we mark it as present in the queue. We only enqueue it again after it has been removed from the queue. This ensures that at any given time, each vertex can appear in the queue at most once. This takesO(V).
Hence, the overall space complexity is O(V + E). ------ Need to explore this more -----
Key Observations
Since all edge weights are non-negative, processing the node with the smallest tentative arrival time guarantees that its shortest arrival time has been found. We can then explore its neighbours and attempt to improve their arrival times, provided they are reached before their respective disappearing times.
This is the core greedy principle behind Dijkstra's algorithm.