1. Description
Consider a directed network of n nodes numbered 1 through n.
Each entry times[i] = (u$_i$, v$_i$, w$_i$) describes an edge from u$_i$ to v$_i$ with travel time w$_i$.
A signal starts at node k at time 0. Return the earliest time by which every node has received it, or -1 if any node is unreachable.
2. Example
Example 1
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
Explanation: Nodes 1 and 3 receive the signal at time 1, and node 4 receives it at time 2.
Example 2
Input: times = [[1,2,1]], n = 2, k = 1
Output: 1
Explanation: Node 2 receives the signal one time unit after it is sent from node 1.
Example 3
Input: times = [[1,2,1]], n = 2, k = 2
Output: -1
Explanation: The edge only leads from node 1 to node 2, so a signal starting at node 2 cannot reach node 1.
3. Constraints
- 1 <= k <= n <= 100
- 1 <= times.length <= 6000
- times[i].length == 3
- 1 <= u$_i$, v$_i$ <= n
- u$_i$ != v$_i$
- 0 <= w$_i$ <= 100
- Each ordered pair (u$_i$, v$_i$) occurs at most once.
4. Solutions
Dijkstra
n = number of nodes, m = times.size()
Time complexity: O(n + m log n)
Space complexity: O(n + m)
| |