Introduction
This blog will discuss the solution to the problem of finding minimum edges connected to node B to be removed from undirected graph to remove any existing path between nodes A and B.
Problem Statement
Here we are given N, M, A, and B, where N denotes the number of vertices, M denotes the number of edges in the graph, and A and B denote the nodes. We are also given an array edges[] [] which is of size M, here edge is represented by edges[i] [0] and edges[i][1]. Our task is to find the minimum edges connected to node B, which need to be removed such that no path exists between nodes A and B.
Some Examples
Example 1:
Input:
N = 5, M = 5, A = 1, B = 4
edges[] [] ={{1, 2}, {3, 4}, {4, 5}, {2, 5}, {1, 3}}
Output:
2
Explanation:
Indexes 3, 4 from the matrix edges[][] must be removed because they are in the path of A and B.
Example 2:
Input:
N = 7, M = 8, A = 2, B = 6
edges[] [] = {{2, 3}, {4, 5}, {4, 3}, {5, 6}, {1, 2}, {6, 7}, {2, 6}, {7, 2}}
Output:
3
Explanation:
Indexes 0, 5, 6 from the matrix edges[][] must be removed because they are in the path of A and B.
DFS Approach
To find the minimum edges connected to node B to be removed from undirected graph to remove any existing path between nodes A and B. We will solve this problem using a depth-first search. As we can see from the problem, we need to remove edges that are connected to node B so that there remains no existing path from A to B.
If A=1, B=3 and there are two edges {1, 2}, {2, 3} then if we remove any one from these two edges, this path would become non-existent.
Steps of Algorithm
- We will first create an adjacency matrix graph[] [], and this matrix will store the edge between two nodes.
- We will initialize a visited array to mark the visited node.
- Now, we will create a variable named cnt to store the count of edges needed to be removed from the graph.
- After that, we will iterate through all nodes of the graph, and we will check if there exists a path from the current node to A. If it is also directly connected to B, we will increment the cnt.
- After the whole iteration is over, then we will return cnt.