## 743. Network Delay Time

There are N network nodes, labelled 1 to N.

Given 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 -1.

Note:

1. N will be in the range [1, 100].
2. K will be in the range [1, N].
3. The length of times will be in the range [1, 6000].
4. All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 1 <= w <= 100.

b'
\n\n

#### Approach #1: Depth-First Search [Accepted]

\n

Intuition

\n

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.

\n

Algorithm

\n

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.

\n

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

Complexity Analysis

\n
\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 .

\n
• \n
• \n

Space Complexity: , the size of the graph (), plus the size of the implicit call stack in our DFS ().

\n
• \n
\n
\n

#### Approach #2: Dijkstra\'s Algorithm [Accepted]

\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

Basic Implementation\n

\n

Heap Implementation

\n\n

Complexity Analysis

\n
\n
• \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.

\n
• \n
• \n

Space Complexity: , the size of the graph (), plus the size of the other objects used ().

\n
• \n
\n
\n

Analysis written by: @awice.

\n
'