664. Find Shortest Path with K Hops
You are given a positive integer n representing the number of nodes in a 0-indexed, undirected, weighted, and connected graph. You are also provided with a 2D array edges where each element edges[i] = [u, v, w] indicates an edge between nodes u and v with weight w. Additionally, you are given two distinct nodes s and d, and a positive integer k.
Your task is to compute the shortest path from s to d if you are allowed to "hop over" (i.e., set the weight of) at most k edges to 0. In other words, you may choose up to k edges along your route and treat their weight as 0, thereby reducing the overall cost.
Return the length of the shortest path from s to d under these conditions.
Example 1:
Input : n = 5, edges = [[0,1,3],[0,2,5],[1,3,4],[2,3,2],[3,4,7]], s = 0, d = 4, k = 1
Output : 7
Explanation :
In this example, there are multiple paths connecting node 0 to node 4. Without any hops, the path 0 → 1 → 3 → 4 has a total cost of 3 + 4 + 7 = 14, and the alternative path 0 → 2 → 3 → 4 also costs 5 + 2 + 7 = 14. However, since you are allowed to set the weight of one edge to 0, you can reduce the cost significantly. For instance, if you choose to hop over the edge between nodes 3 and 4 on the path 0 → 1 → 3 → 4, the total cost becomes 3 + 4 + 0 = 7, which is the minimum possible under the given conditions.
Example 2:
Input : n = 6, edges = [[0,1,2],[1,2,3],[2,3,6],[3,4,1],[4,5,4],[0,5,15]], s = 0, d = 5, k = 2
Output : 0
Explanation :
In this example, a possible path from node 0 to node 5 without using any hops is 0 → 1 → 2 → 3 → 4 → 5, which has a total cost of 2 + 3 + 6 + 1 + 4 = 16, and the direct edge from 0 to 5 costs 15. However, by utilizing up to 2 hops, you can further reduce the cost. For example, if you follow the path 0 → 1 → 2 → 3 → 4 → 5 and choose to hop over the edges from 2 to 3 and from 4 to 5, the cost becomes 2 + 3 + 0 + 1 + 0 = 6, or if you follow the path 0 → 5 and choose to hop over the edges from 0 to 5, the cost becomes 0 , which is the optimal solution.
Now Your Turn!
Pick the correct output for the given inputInput: n = 4, edges = [[0,1,10],[1,2,5],[2,3,7]], s = 0, d = 3, k = 1
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 ≤ 500
- n - 1 ≤ edges.length ≤ min(10⁴, n * (n - 1) / 2)
- Each edge is represented as an array of 3 integers
- 0 ≤ u, v < n
- 1 ≤ w ≤ 10⁶
- 0 ≤ s, d, k < n
- s ≠ d
- The graph is connected, with no repeated edges or self-loops.