Problem Description
You are given an undirected weighted connected graph with n nodes (0-indexed) and an edge list. Additionally, you are provided with two nodes s and d, and a positive integer k. The objective is to determine the shortest path from s to d when you are allowed to set the weight of at most k edges used in the path to 0.
Key Insights
- The problem is a variant of the traditional shortest path but with an extra twist: you can “hop” over (set weight = 0) on at most k edges.
- Each state in the traversal is defined by (current_node, hops_used) because the cost and the possibility to hop further depends on how many hops are already used.
- We can use a modified Dijkstra’s algorithm, where each node can have multiple states based on the number of hops used so far.
- We maintain a distance table indexed by (node, hops_used) and use a min-priority queue (heap) for exploring the best current option.
- The two options at every edge are: traverse normally (adding the weight) or hop (if hops available) and add 0 cost.
Space and Time Complexity
Time Complexity: O((V + E) * k * log(V * k)) – since every state (node, hops_used) is processed using a priority queue. Space Complexity: O(V * k) – storing the distance for each node for different hops used.
Solution
We solve the problem using a modified Dijkstra’s algorithm that incorporates the number of hops used as an extra dimension in the state. For every state (current_node, hops_used) reached with some cost, we evaluate each adjacent edge in two ways:
- Without hopping: the new cost is the current cost plus the edge’s weight, and the hops_used remains unchanged.
- With hopping (if hops_used is less than k): the new cost remains unchanged (edge weight becomes 0), and hops_used is incremented by 1.
A min-heap is used to always expand the state with the smallest current cost. When we reach the destination, we can return the minimum cost.