Find Shortest Path with K Hops - Problem

Imagine you're a delivery driver with a special power: you can teleport through at most k roads to make them cost zero! ๐Ÿššโœจ

You're given an undirected weighted graph with n nodes connected by edges. Each edge has a weight representing the travel cost. Your mission is to find the shortest path from source node s to destination node d, but here's the twist: you can make up to k edges have zero weight by "hopping" over them.

Goal: Find the minimum total cost to travel from s to d when you can eliminate the cost of at most k edges.

Input: Number of nodes n, array of edges [u, v, weight], source s, destination d, and maximum hops k.

Output: The minimum path cost with the given hop constraint.

Input & Output

example_1.py โ€” Basic Triangle Graph
$ Input: n = 3, edges = [[0,1,5], [1,2,3], [0,2,8]], s = 0, d = 2, k = 1
โ€บ Output: 3
๐Ÿ’ก Note: We have a triangle: 0--(5)--1--(3)--2 with direct edge 0--(8)--2. With k=1, we can make one edge free. Best strategy: take path 0โ†’1โ†’2, make edge 0โ†’1 free (cost 0), then pay 3 for edge 1โ†’2. Total cost = 3.
example_2.py โ€” No Hops Needed
$ Input: n = 3, edges = [[0,1,1], [1,2,1], [0,2,3]], s = 0, d = 2, k = 2
โ€บ Output: 2
๐Ÿ’ก Note: Direct path 0โ†’1โ†’2 costs only 2, which is better than the direct edge 0โ†’2 costing 3. Even though we have 2 hops available, we don't need to use any since the cheapest path is already optimal.
example_3.py โ€” Use All Hops
$ Input: n = 4, edges = [[0,1,10], [1,2,10], [2,3,10], [0,3,25]], s = 0, d = 3, k = 2
โ€บ Output: 10
๐Ÿ’ก Note: Path 0โ†’1โ†’2โ†’3 normally costs 30. With k=2 hops, we can make edges 0โ†’1 and 1โ†’2 free, leaving only edge 2โ†’3 costing 10. This beats the direct path 0โ†’3 costing 25.

Constraints

  • 2 โ‰ค n โ‰ค 1000
  • 1 โ‰ค edges.length โ‰ค min(n*(n-1)/2, 8000)
  • edges[i].length == 3
  • 0 โ‰ค ui, vi < n
  • ui โ‰  vi
  • 0 โ‰ค wi โ‰ค 104
  • 0 โ‰ค s, d < n
  • s โ‰  d
  • 0 โ‰ค k โ‰ค min(edges.length, 50)
  • The graph is connected
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen