Menu
CoddyTech

Network Delay Time

A network has n nodes labelled 1 to n. Link times[i] = [u, v, w] carries a signal from node u to node v in w units of time, in that direction only.

A signal leaves node k at time 0 and travels along every link it can. Return the time when the last node receives it, or -1 if some node never does.

Function

networkDelayTime(times: integer-2d-array, n: integer, k: integer) → integer
timesinteger-2d-array
the directed links, each as [u, v, w]
ninteger
the number of nodes
kinteger
the node that sends the signal
Returnsinteger
the time when the last node receives the signal, or -1

Constraints

  • 2 ≤ n ≤ 3000
  • 1 ≤ times.length ≤ 4000
  • times[i].length = 3
  • 1 ≤ u, v ≤ n and u ≠ v
  • 0 ≤ w ≤ 100
  • No two links share both the same u and the same v.
  • 1 ≤ k ≤ n

Examples

Input
times = [[1, 2, 4], [1, 3, 1], [3, 2, 2], [2, 4, 1]]n = 4k = 1
Output
4
Explanation
The direct link reaches node 2 at time 4, but the route through node 3 arrives at 1 + 2 = 3. Node 4 hears the signal last, at 3 + 1 = 4.
challenge icon

Follow-up

Suppose the signal fades after crossing m links. How do you find the time the last node hears it under that limit?

Reset code
def networkDelayTime(times, n, k):
    # Write code here

Test #1

Test #2

Test #3

Arguments

times = [[1, 2, 4], [1, 3, 1], [3, 2, 2], [2, 4, 1]]
n = 4
k = 1

Expected Output

4