You are given a network of `n` nodes labeled from `1` to `n`. Travel times are described by a list `times`, where each entry `times[i] = [u, v, w]` means a signal takes `w` units of time to travel along a directed edge from node `u` to node `v`.
A signal is emitted from a single source node `k`. Return the amount of time it takes for the signal to reach every node in the network. If it is impossible for at least one node to receive the signal, return `-1`.
Because a node lights up as soon as the signal first arrives, the time for the whole network to be covered is the latest of all the individual arrival times.
Example 1
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
From node 2 the signal reaches node 1 at time 1 and node 3 at time 1, then continues from 3 to node 4 at time 2. The slowest arrival is 2.
Example 2
Input: times = [[1,2,1]], n = 2, k = 2
Output: -1
The only edge points from 1 to 2, so starting at node 2 there is no way to reach node 1. One node stays unreachable, so the answer is -1.
Constraints
1 <= k <= n <= 1001 <= times.length <= 6000times[i].length == 31 <= u_i, v_i <= nu_i != v_i0 <= w_i <= 100All pairs (u_i, v_i) are unique (no multiple edges).See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI