N network nodes, labelled
times, a list of travel times as directed edges
times[i] = (u, v, w), where
u is the source node,
v is the target node, and
w is the time it takes for a signal to travel from source to target.
Now, we send a signal from a certain node
K. How long will it take for all nodes to receive the signal? If it is impossible, return
Nwill be in the range
Kwill be in the range
timeswill be in the range
times[i] = (u, v, w)will have
1 <= u, v <= Nand
1 <= w <= 100.
Let\'s record the time
dist[node] when the signal reaches the node. If some signal arrived earlier, we don\'t need to broadcast it anymore. Otherwise, we should broadcast the signal.
dist[node], the earliest that we arrived at each
node. When visiting a
elapsed time has elapsed, if this is the currently-fastest signal at this node, let\'s broadcast signals from this node.
To speed things up, at each visited node we\'ll consider signals exiting the node that are faster first, by sorting the edges.\n\n
Time Complexity: where is the length of
times. We can only fully visit each node up to times, one per each other node. Plus, we have to explore every edge and sort them. Sorting each small bucket of outgoing edges is bounded by sorting all of them, because of repeated use of the inequality .
Space Complexity: , the size of the graph (), plus the size of the implicit call stack in our DFS ().\n
Intuition and Algorithm\n
We use Dijkstra\'s algorithm to find the shortest path from our source to all targets. This is a textbook algorithm, refer to this link for more details.\n
Dijkstra\'s algorithm is based on repeatedly making the candidate move that has the least distance travelled.\n
In our implementations below, we showcase both (basic) and (heap) approaches.\n
Time Complexity: m where is the length of
times in the basic implementation, and in the heap implementation, as potentially every edge gets added to the heap.
Space Complexity: , the size of the graph (), plus the size of the other objects used ().\n
Analysis written by: @awice.\n