VOOZH about

URL: https://www.geeksforgeeks.org/dsa/shortest-distance-between-given-nodes-in-a-bidirectional-weighted-graph-by-removing-any-k-edges/

⇱ Shortest distance between given nodes in a bidirectional weighted graph by removing any K edges - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shortest distance between given nodes in a bidirectional weighted graph by removing any K edges

Last Updated : 23 Jul, 2025

Given a positive integer K and a weighted undirected connected graph of N nodes and E edges as an array Edges[] of the type {u, v, W} representing the edges between Node u and Node v having weight W, the task is to find the shortest distance between the two given nodes S and D after reducing the cost of at most K edges to 0

Examples:

Input: N = 5, K = 1, Edges[][] = {{0, 1, 1}, {0, 4, 1}, {1, 2, 2}, {2, 3, 4},  {4, 3, 7}}, s = 0, d = 3
Output: 1
Explanation:
Below is the graph for the given test case:

👁 Image

There are 2 possible routes between 0 and 3 viz. {0->1->2->3} and {0->4->3}
after reducing the distance of edge 4->3 to zero, the second route becomes 0->(4, 3) and hence the minimum distance is 1.


Input: N = 5, K = 2, Edges[][] = {{0, 1, 2}, {0, 2, 3}, {2, 1, 2}, {2, 3, 1}, {3, 1, 2}, {3, 4, 3}, {4, 2, 4}}, s = 0, d = 3
Ouput: 2

Approach: The given problem can be solved using DFS Traversal and storing all possible paths between the two given nodes. Follow the steps below to solve the given problem:

Below is the implementation of the above approach:


Output
1

Time Complexity: O((N*log N)NN)
Auxiliary Space: O(N2)

Efficient Approach: The above approach can also be optimized at the step where sorting is performed after finding all possible paths. Instead of sorting, the idea is to use MinHeap to calculate the sum of K largest weights in the graph to reduce the time complexity to O(N*log K) for that steps.

Below is the implementation of the above approach:


Output
1

Time Complexity: O((N*log K)NN)
Auxiliary Space: O(N2)

Comment