Skip to content
BytePatterns

Signal Spread Time

MediumGraphs#dijkstra#shortest-path#min-heap~30m

Problem

A network has n relays numbered from 0 and a list of one-way links (u, v, t): a signal at relay u reaches relay v after t minutes, where t is 0 or more. A signal leaves relay source at minute 0 and every relay forwards it along all of its links the moment it arrives. Return the minute at which the last relay receives the signal, or -1 if some relay never receives it.

Examples

Input:  n = 4, source = 0
        links = [(0, 1, 2), (0, 2, 5), (1, 2, 1), (2, 3, 3)]
Output: 6
Why:    relay 2 hears it at minute 3 through relay 1, so relay 3 hears it at 6
Input:  n = 3, links = [(0, 1, 4)], source = 0
Output: -1
Why:    nothing ever links to relay 2
Input:  n = 1, links = [], source = 0
Output: 0
Why:    edge case, the source already has the signal

Hints

0 / 3

Stuck on the idea rather than the code? Dijkstra's Algorithm covers it.