Number of pairs such that path between pairs has the two vertices A and B

05 Dec, 2021
Given an undirected connected graph and two vertices A and B, the task is to find the number of pairs of vertices {X, Y} such that any path from X to Y contains both vertices A and B.Note: 
{ X, Y } is treated equivalent to { Y, X }.
X != A, X != B, Y != A and Y != B.
Examples:  
For the above graph: Input: A = 3, B = 5 Output:4 Explanation: There are four pairs { X, Y } such that all the paths from the source X to the destination Y contain the vertices A, B. They are: {1, 6}, {1, 7}, {2, 6} and {2, 7}. 
For the above graph: Input: A = 2, B = 1 Output: 1 Explanation: There is only one pair { X, Y } such that all the paths from the source X to the destination Y contain the vertices A, B. That is: {4, 3}. 
 
Approach: 
For the given graph, if for any pair {X, Y}, if some other path exists between them apart from the given vertices A and B, then those two vertices are not included in the final answer. That is because we need the count of pairs such that any path from those pairs consists the vertices A and B.
Therefore, we are interested in pairs of vertices { X, Y } such that deleting the vertex A(while going from B) breaks the connection from X to Y and deleting the vertex B(while going from A) breaks the connection from X to Y.
In other words the pair {X, Y} interests us if X and Y belong to the different components of the graph both when removing A and when removing B.
Therefore, in order to find the above pairs, the following steps are followed: 
Consider a random directed connected graph where some group of nodes which are interconnected is connected to A and some group of interconnected nodes are connected to B. A and B may or may not have nodes between them.
What if we remove both A and B? Then the graph can either become disconnected or remain connected.
If the graph remains connected, then no pair of vertices exists because there are other paths in the graph for all the pairs {X, Y} without the vertices A and B in it.
If the graph becomes disconnected, then there arise two cases: On removing vertices A and B, the graph is converted to two disconnected components.On removing vertices A and B, the graph is converted to three disconnected components.
On removing vertices A and B, the graph is converted to two disconnected components.On removing vertices A and B, the graph is converted to three disconnected components.
On removing vertices A and B, the graph is converted to two disconnected components.
On removing vertices A and B, the graph is converted to three disconnected components.
If on removing vertices A and B, the graph is converted to two disconnected components, then three cases arise:  
When there is a group of interconnected nodes connected to the vertex A, some independent nodes are connected to A and B and the vertex B is the leaf node of the graph:  
When there is a group of interconnected nodes connected to the vertex A, some independent nodes are connected to A and B and the vertex B is the leaf node of the graph:  
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex B. So no pair exists.When there is a group of interconnected nodes connected to the vertex B, some independent nodes are connected to A and B and the vertex A is the leaf node of the graph:  
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex B. So no pair exists.
When there is a group of interconnected nodes connected to the vertex B, some independent nodes are connected to A and B and the vertex A is the leaf node of the graph:  
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex A. So no pair exists.When there are no nodes between vertex A and vertex B and neither of the vertices A and B are the leaf nodes of the graph:  
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex A. So no pair exists.
When there are no nodes between vertex A and vertex B and neither of the vertices A and B are the leaf nodes of the graph:  
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. Here, any one of the vertex of one component can be paired up with any vertex of the other component. Therefore, the number of pairs in this graph becomes the product of the count of number of interconnected nodes in component 1 and component two.
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. Here, any one of the vertex of one component can be paired up with any vertex of the other component. Therefore, the number of pairs in this graph becomes the product of the count of number of interconnected nodes in component 1 and component two.
If on removing vertices A and B, the graph is converted to three disconnected components, then only one case arises:  
When there is a group of interconnected nodes connected to vertex A, vertex B and there is another group of nodes between vertex A and vertex B and none of the vertices A and B are the leaf nodes:  
When there is a group of interconnected nodes connected to vertex A, vertex B and there is another group of nodes between vertex A and vertex B and none of the vertices A and B are the leaf nodes:  
In this case, the component between vertex A and B can be discarded due to the above-mentioned reasons. And, once its discarded, it is directly the case 3 in the two-component graph. The same concept is applied to find the number of vertices.
In this case, the component between vertex A and B can be discarded due to the above-mentioned reasons. And, once its discarded, it is directly the case 3 in the two-component graph. The same concept is applied to find the number of vertices.
Therefore, the above idea is implemented in the following steps:  
Store the graph as adjacency list by using vector STL.Run DFS such that we fix the vertex B as if we removed it. This can be done using base condition of the DFS function i.e. the call is returned on reaching the vertex B.Count the vertices that can not be reached by A after removing B.Repeat the above two steps by fixing the vertex A and counting the number of vertices that cannot be reached by B after removing the vertex A.Store both counts in two different variables. This represents the count of vertices set first on removing B and then removing A.Multiplying both the counts is the required answer.
Store the graph as adjacency list by using vector STL.
Run DFS such that we fix the vertex B as if we removed it. This can be done using base condition of the DFS function i.e. the call is returned on reaching the vertex B.
Count the vertices that can not be reached by A after removing B.
Repeat the above two steps by fixing the vertex A and counting the number of vertices that cannot be reached by B after removing the vertex A.
Store both counts in two different variables. This represents the count of vertices set first on removing B and then removing A.
Multiplying both the counts is the required answer.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to find the number// of pairs such that the path between// every pair contains two given vertices #include <bits/stdc++.h>using namespace std; int cnt, num_vertices, num_edges, a, b; // Function to perform DFS on the given graph// by fixing the a vertexvoid dfs(int a, int b, vector<int> v[], int vis[]){    // To mark a particular vertex as visited    vis[a] = 1;     // Variable to store the count of the    // vertices which can be reached from a    cnt++;     // Performing the DFS by iterating over    // the visited array    for (auto i : v[a]) {         // If the vertex is not visited        // and removing the vertex b        if (!vis[i] && i != b)            dfs(i, b, v, vis);    }} // Function to return the number of pairs// such that path between any two pairs// consists the given two vertices A and Bvoid Calculate(vector<int> v[]){     // Initializing the visited array    // and assigning it with 0's    int vis[num_vertices + 1];    memset(vis, 0, sizeof(vis));     // Initially, the count of vertices is 0    cnt = 0;     // Performing DFS by removing the vertex B    dfs(a, b, v, vis);     // Count the vertices which cannot be    // reached after removing the vertex B    int ans1 = num_vertices - cnt - 1;     // Again reinitializing the visited array    memset(vis, 0, sizeof(vis));     // Setting the count of vertices to 0 to    // perform the DFS again    cnt = 0;     // Performing the DFS by removing the vertex A    dfs(b, a, v, vis);     // Count the vertices which cannot be    // reached after removing the vertex A    int ans2 = num_vertices - cnt - 1;     // Multiplying both the vertices set    cout << ans1 * ans2 << "\n";} // Driver codeint main(){    num_vertices = 7, num_edges = 7, a = 3, b = 5;     int edges[][2] = { { 1, 2 },                       { 2, 3 },                       { 3, 4 },                       { 4, 5 },                       { 5, 6 },                       { 6, 7 },                       { 7, 5 } };    vector<int> v[num_vertices + 1];     // Loop to store the graph    for (int i = 0; i < num_edges; i++) {        v[edges[i][0]].push_back(edges[i][1]);        v[edges[i][1]].push_back(edges[i][0]);    }     Calculate(v);    return 0;}
// Java program to find the number// of pairs such that the path between// every pair contains two given verticesimport java.util.*; class GFG{static int N = 1000001;static int c, n, m, a, b;  // Function to perform DFS on the given graph// by fixing the a vertexstatic void dfs(int a, int b, Vector<Integer> v[], int vis[]){    // To mark a particular vertex as visited    vis[a] = 1;      // Variable to store the count of the    // vertices which can be reached from a    c++;      // Performing the DFS by iterating over    // the visited array    for (int i : v[a]) {          // If the vertex is not visited        // and removing the vertex b        if (vis[i] == 0 && i != b)            dfs(i, b, v, vis);    }}  // Function to return the number of pairs// such that path between any two pairs// consists of the given two vertices A and Bstatic void Calculate(Vector<Integer> v[]){      // Initializing the visited array    // and assigning it with 0's    int []vis = new int[n + 1];    Arrays.fill(vis, 0);     // Initially, the count of vertices is 0    c = 0;      // Performing DFS by removing the vertex B    dfs(a, b, v, vis);      // Count the vertices which cannot be    // reached after removing the vertex B    int ans1 = n - c - 1;      // Again reinitializing the visited array    Arrays.fill(vis, 0);      // Setting the count of vertices to 0 to    // perform the DFS again    c = 0;      // Performing the DFS by removing the vertex A    dfs(b, a, v, vis);      // Count the vertices which cannot be    // reached after removing the vertex A    int ans2 = n - c - 1;      // Multiplying both the vertices set    System.out.print(ans1 * ans2+ "\n");}  // Driver codepublic static void main(String[] args){    n = 7;    m = 7;    a = 3;    b = 5;      int edges[][] = { { 1, 2 },                       { 2, 3 },                       { 3, 4 },                       { 4, 5 },                       { 5, 6 },                       { 6, 7 },                       { 7, 5 } };    Vector<Integer> []v = new Vector[n + 1];    for(int i= 0; i <= n; i++) {        v[i] = new Vector<Integer>();    }    // Loop to store the graph    for (int i = 0; i < m; i++) {        v[edges[i][0]].add(edges[i][1]);        v[edges[i][1]].add(edges[i][0]);    }      Calculate(v);}} // This code is contributed by Rajput-Ji
# Python 3 program to find the number# of pairs such that the path between# every pair contains two given vertices N = 1000001c = 0n = 0m = 0a = 0b = 0 # Function to perform DFS on the given graph# by fixing the a vertexdef dfs(a,b,v,vis):    global c    # To mark a particular vertex as visited    vis[a] = 1    # Variable to store the count of the    # vertices which can be reached from a    c += 1     # Performing the DFS by iterating over    # the visited array    for i in v[a]:        # If the vertex is not visited        # and removing the vertex b        if (vis[i]==0 and i != b):            dfs(i, b, v, vis) # Function to return the number of pairs# such that path between any two pairs# consists of the given two vertices A and Bdef Calculate(v):    global c         # Initializing the visited array    # and assigning it with 0's    vis = [0 for i in range(n + 1)]     # Initially, the count of vertices is 0    c = 0     # Performing DFS by removing the vertex B    dfs(a, b, v, vis)     # Count the vertices which cannot be    # reached after removing the vertex B    ans1 = n - c - 1     # Again reinitializing the visited array    vis = [0 for i in range(len(vis))]     # Setting the count of vertices to 0 to    # perform the DFS again    c = 0     # Performing the DFS by removing the vertex A    dfs(b, a, v, vis)     # Count the vertices which cannot be    # reached after removing the vertex A    ans2 = n - c - 1     # Multiplying both the vertices set    print(ans1 * ans2) # Driver codeif __name__ == '__main__':    n = 7    m = 7    a = 3    b = 5     edges = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 5]]    v = [[] for i in range(n + 1)]     # Loop to store the graph    for i in range(m):        v[edges[i][0]].append(edges[i][1])        v[edges[i][1]].append(edges[i][0])     Calculate(v) # This code is contributed by Surendra_Gangwar
// C# program to find the number// of pairs such that the path between// every pair contains two given verticesusing System;using System.Collections.Generic; class GFG{static int N = 1000001;static int c, n, m, a, b; // Function to perform DFS on the given graph// by fixing the a vertexstatic void dfs(int a, int b, List<int> []v, int []vis){    // To mark a particular vertex as visited    vis[a] = 1;     // Variable to store the count of the    // vertices which can be reached from a    c++;     // Performing the DFS by iterating over    // the visited array    foreach (int i in v[a]) {         // If the vertex is not visited        // and removing the vertex b        if (vis[i] == 0 && i != b)            dfs(i, b, v, vis);    }} // Function to return the number of pairs// such that path between any two pairs// consists of the given two vertices A and Bstatic void Calculate(List<int> []v){     // Initializing the visited array    // and assigning it with 0's    int []vis = new int[n + 1];    for(int i = 0; i < n + 1; i++)        vis[i] = 0;     // Initially, the count of vertices is 0    c = 0;     // Performing DFS by removing the vertex B    dfs(a, b, v, vis);     // Count the vertices which cannot be    // reached after removing the vertex B    int ans1 = n - c - 1;     // Again reinitializing the visited array    for(int i = 0; i < n + 1; i++)        vis[i] = 0;     // Setting the count of vertices to 0 to    // perform the DFS again    c = 0;     // Performing the DFS by removing the vertex A    dfs(b, a, v, vis);     // Count the vertices which cannot be    // reached after removing the vertex A    int ans2 = n - c - 1;     // Multiplying both the vertices set    Console.Write(ans1 * ans2+ "\n");} // Driver codepublic static void Main(String[] args){    n = 7;    m = 7;    a = 3;    b = 5;     int [,]edges = { { 1, 2 },                    { 2, 3 },                    { 3, 4 },                    { 4, 5 },                    { 5, 6 },                    { 6, 7 },                    { 7, 5 } };    List<int> []v = new List<int>[n + 1];    for(int i= 0; i <= n; i++) {        v[i] = new List<int>();    }    // Loop to store the graph    for (int i = 0; i < m; i++) {        v[edges[i,0]].Add(edges[i,1]);        v[edges[i,1]].Add(edges[i,0]);    }     Calculate(v);}} // This code is contributed by Princi Singh
<script>    // Javascript program to find the number    // of pairs such that the path between    // every pair contains two given vertices         let N = 1000001;    let c, n, m, a, b;     // Function to perform DFS on the given graph    // by fixing the a vertex    function dfs(a, b, v, vis)    {        // To mark a particular vertex as visited        vis[a] = 1;         // Variable to store the count of the        // vertices which can be reached from a        c++;         // Performing the DFS by iterating over        // the visited array        for(let i of v[a]) {             // If the vertex is not visited            // and removing the vertex b            if (vis[i] == 0 && i != b)                dfs(i, b, v, vis);        }    }     // Function to return the number of pairs    // such that path between any two pairs    // consists of the given two vertices A and B    function Calculate(v)    {         // Initializing the visited array        // and assigning it with 0's        let vis = new Array(n + 1);        for(let i = 0; i < n + 1; i++)            vis[i] = 0;         // Initially, the count of vertices is 0        c = 0;         // Performing DFS by removing the vertex B        dfs(a, b, v, vis);         // Count the vertices which cannot be        // reached after removing the vertex B        let ans1 = n - c - 1;         // Again reinitializing the visited array        for(let i = 0; i < n + 1; i++)            vis[i] = 0;         // Setting the count of vertices to 0 to        // perform the DFS again        c = 0;         // Performing the DFS by removing the vertex A        dfs(b, a, v, vis);         // Count the vertices which cannot be        // reached after removing the vertex A        let ans2 = n - c - 1;         // Multiplying both the vertices set        document.write((ans1 * ans2)+ "</br>");    }         n = 7;    m = 7;    a = 3;    b = 5;      let edges = [ [ 1, 2 ],                    [ 2, 3 ],                    [ 3, 4 ],                    [ 4, 5 ],                    [ 5, 6 ],                    [ 6, 7 ],                    [ 7, 5 ] ];    let v = new Array(n + 1);    for(let i= 0; i <= n; i++) {        v[i] = [];    }    // Loop to store the graph    for (let i = 0; i < m; i++) {        v[edges[i][0]].push(edges[i][1]);        v[edges[i][1]].push(edges[i][0]);    }      Calculate(v); // This code is contributed by divyeshrabadiya07.</script>
4
 
Time Complexity Analysis:  
Here, DFS is performed twice. Therefore, the overall time complexity is O(V + E).
Auxiliary Space : O(V + E)
SURENDRA_GANGWAR
Rajput-Ji
princi singh
Akanksha_Rai
pankajsharmagfg
divyeshrabadiya07
ashutoshsinghgeeksforgeeks
Algorithms
Backtracking
Combinatorial
Graph
Recursion
Recursion
Graph
Combinatorial
Backtracking
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.