AlgoFrames

Network delay time

Standard · Write code · about 15 min

A signal starts at node k and travels along directed links. Each entry [u, v, w] in times is a link from u to v that takes w time units. Nodes are numbered 1 to n. Return the time until every node has the signal, or -1 when some node never gets it.

Example 1

Input:

[[[2,1,1],[2,3,1],[3,4,1]],4,2]

Output:

2

Nodes are drawn with labels 1 to 4 in the lesson and 0 to 3 here.

Example 2

Input:

[[[1,2,1]],2,2]

Output:

-1

Node 1 has no incoming link from node 2.

Constraints

  • 1 ≤ k ≤ n ≤ 100
  • 1 ≤ times.length ≤ 6000
  • 0 ≤ w ≤ 100
  • Every link [u, v, w] has u ≠ v.

Learn the idea first: Dijkstra's algorithm, a visual lesson.

More Dijkstra's algorithm problems