Menu
CoddyTech

Network Delay Time

A network has n nodes, labelled from 1 to n. You get its links as a list times, where times[i] = [u, v, w] means a signal sent from node u reaches node v after w units of time. Links work in one 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
Node 3 hears the signal at time 1. Node 2 could hear it at 4 over its direct link, but the route through node 3 arrives at 1 + 2 = 3, and node 4 hears it at 3 + 1 = 4. Node 4 is last, at time 4.

lock icon+16 hidden tests on Submit

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 cases

Case 1

Case 2

Case 3

Input

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

Expected

4