Minimum Cost to Repair Edges to Traverse a Graph
You are given an undirected graph with n nodes labeled from 0 to n - 1.
The graph contains m edges described by a 2D array edges, where: edges[i] = [ui, vi, wi]
represents an undirected edge between nodes ui and vi with repair cost wi.
Initially, all edges are damaged.
You are allowed to choose a non-negative integer money.
After choosing money, all edges with repair cost ≤ money become usable.
All edges with repair cost greater than money remain damaged and cannot be used.
Your goal is to determine the minimum value of money such that it is possible to travel from node 0 to node n - 1 using at most k edges.
Return the minimum required money, or -1 if it is impossible.
Example 1:
Input: n = 4, edges = [[0,1,3],[1,3,4],[0,2,8],[2,3,2]], k = 2
Output: 4
Explanation:
If money = 4, edges with cost ≤ 4 become usable:
- [0,1,3]
- [1,3,4]
- [2,3,2]
Now the path 0 → 1 → 3 uses 2 edges (≤ k).
If money < 4, this path is not available.
Hence, answer = 4.
Example 2:
Input: n = 5, edges = [[0,1,5],[1,2,6],[2,4,4],[0,3,10],[3,4,3]], k = 2
Output: 10
Explanation:
If money = 10, all edges with cost ≤ 10 are usable.
This enables path 0 → 3 → 4, which uses exactly 2 edges.
If money < 10, node 3 is unreachable from node 0 within 2 edges.
Therefore, the minimum required money is 10.
Now Your Turn!
Pick the correct output for the given inputInput: n = 4, edges = [[0,1,2],[1,3,6],[0,2,4],[2,3,5]], k = 2
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 2 ≤ n ≤ 5 * 104
- 1 ≤ m = edges.length ≤ 105
- edges[i] = [ui, vi, wi]
- 0 ≤ ui, vi < n
- ui ≠ vi
- 1 ≤ wi ≤ 109
- 1 ≤ k ≤ n
- The graph contains no self-loops
- The graph contains no duplicate edges
- The graph is undirected