Find Shortest Path with K Hops - Problem
You are given a positive integer n which is the number of nodes of a 0-indexed undirected weighted connected graph and a 0-indexed 2D array edges where edges[i] = [ui, vi, wi] indicates that there is an edge between nodes ui and vi with weight wi.
You are also given two nodes s and d, and a positive integer k. Your task is to find the shortest path from s to d, but you can hop over at most k edges. In other words, make the weight of at most k edges 0 and then find the shortest path from s to d.
Return the length of the shortest path from s to d with the given condition.
Input & Output
Example 1 — Basic Graph with 2 Free Hops
$
Input:
n = 4, edges = [[0,1,10],[0,2,1],[1,2,5],[2,3,1]], s = 0, d = 3, k = 2
›
Output:
1
💡 Note:
Skip edges (0,1) and (1,2), then path 0→2→3 costs 1+1=2, but we can also skip (2,3) and take path 0→2→3 with cost 1+0=1
Example 2 — Linear Chain
$
Input:
n = 3, edges = [[0,1,5],[1,2,5]], s = 0, d = 2, k = 1
›
Output:
5
💡 Note:
Skip one edge: either 0→1 (skip) + 1→2 (cost 5) = 5, or 0→1 (cost 5) + 1→2 (skip) = 5
Example 3 — No Hops Available
$
Input:
n = 3, edges = [[0,1,2],[1,2,3],[0,2,10]], s = 0, d = 2, k = 0
›
Output:
5
💡 Note:
Cannot skip any edges, shortest path is 0→1→2 with cost 2+3=5
Constraints
- 2 ≤ n ≤ 1000
- 1 ≤ edges.length ≤ min(n×(n-1)/2, 2000)
- edges[i].length == 3
- 0 ≤ ui, vi ≤ n-1
- 1 ≤ wi ≤ 106
- 0 ≤ s, d ≤ n-1
- s ≠ d
- 1 ≤ k ≤ n
- Graph is connected
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code