Editor

Signal Delay

#161 · Graphs · Advanced · 150 XP · about 25 min

A network has n computers, numbered 0 to n - 1. Each link [a, b, ms] in links carries messages one way, from computer a to computer b, and takes ms milliseconds. Computer source sends a message, and every computer that receives it passes it on at once along all of its outgoing links.

Write signal_time(n, links, source) that returns how many milliseconds pass until every computer has received the message. If some computer can never receive it, return -1.

Examples

links = [[0, 1, 2], [0, 2, 5], [1, 2, 1], [2, 3, 3]]
signal_time(4, links, 0)  # returns 6
signal_time(2, [[0, 1, 4]], 1)  # returns -1
signal_time(1, [], 0)  # returns 0

In the first network the message reaches computer 2 sooner through computer 1 (2 + 1 = 3 ms) than by the direct link (5 ms), and computer 3 receives it 3 ms after that, at 6 ms.

Constraints

  • 1 <= n <= 1000, with up to 5,000 links.
  • 0 <= ms <= 1000. There can be several links between the same two computers.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.