Approach #1: Depth-First Search [Accepted]


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.


We'll maintain dist[node], the earliest that we arrived at each node. When visiting a node while 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.

Complexity Analysis

  • 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 ().

Approach #2: Dijkstra's Algorithm [Accepted]

Intuition and Algorithm

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.

Dijkstra's algorithm is based on repeatedly making the candidate move that has the least distance travelled.

In our implementations below, we showcase both (basic) and (heap) approaches.

Basic Implementation

Heap Implementation

Complexity Analysis

  • 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 ().

Analysis written by: @awice.