Practice · Shortest paths · 1 of 1

Signal Spread Time

A network has n nodes, numbered from 1 to n. Each entry [u, v, w] in times is a one-way link: a signal at node u reaches node v after w minutes.

A signal starts at node k at minute 0 and travels along every link at once. Return the number of minutes until every node has received it, or -1 if some node can never be reached.

Example 1

Input
times = [[1, 2, 4], [1, 3, 1], [3, 2, 2], [2, 4, 1]], n = 4, k = 1
Output
4
Node 3 hears the signal at minute 1, node 2 at minute 3 by way of node 3 (sooner than the direct 4-minute link), and node 4 at minute 4.

Example 2

Input
times = [[1, 2, 5], [1, 3, 2]], n = 3, k = 2
Output
-1
Links only go one way, and none leaves node 2, so the signal never gets anywhere.

Constraints

  • 1 ≤ k ≤ n ≤ 500
  • times holds 0 to 6000 links. In each, u and v are different nodes from 1 to n, and no (u, v) pair appears twice.
  • 0 ≤ w ≤ 100