Number of Pairs Such that Path Between Pairs has the two Vertices A and B


The article codes points to the number of sets in a chart such that the way between each combine contains two indicated vertices, A and B. It employs a Profundity To begin with, use the Look (DFS) approach to analyse the network of the chart and tally the required pairs. The calculation works by performing two isolated DFS traversals. Within the first traversal, it evacuates vertex B and calculates the number of vertices that can still be reached from vertex A. So also, within the moment traversal, it evacuates vertex A and tallies the number of vertices reachable from vertex B. Subtracting the number of vertices reachable on each path from the total number of vertices in the graph gives the number of unreachable vertices after excluding A and B separately. The calculation at this point increments these two checks to calculate the total number of sentences that satisfy the condition.

Methods Used

  • DFS

  • BFS

DFS

The given code executes an approach based on profundity. To begin with, use DFS to discover the number of sets such that the way between each match contains two given vertices. It employs DFS to tally the number of vertices that can be derived from a specific vertex, barring the other given vertex. By performing DFS twice, once after evacuating vertex B and once after expelling vertex A, the code calculates the number of vertices that cannot be reached in each case. The ultimate result is obtained by duplicating these two counts. This approach analyses the network of the chart utilising DFS and checks the number of vertices that are not reachable after expelling the required vertices. At that point, it calculates the overall number of sets fulfilling the given condition.

Algorithm

  • Begin with the given chart, spoken to by a contiguousness list.

  • Initialise a tally variable (cnt) to 0.

  • Initialise a gone−to cluster (vis) to keep track of gone−to vertices. Check all vertices as unvisited.

  • Perform a depth−first look (DFS) beginning from vertex A:

  • Mark vertex A as visited.

  • Increment the cnt variable by 1.

  • For each adjoining vertex (neighbour) of A:

  • If the neighbour hasn't gone to and hasn't risen to vertex B, recursively call the DFS work on the neighbour.

  • After the DFS from vertex A is total, store the value of cnt in a variable (count 1).

  • Reset the gone−by cluster (vis) and cnt to 0.

  • Perform another DFS beginning at vertex B:

  • Mark vertex B as visited.

  • Increment the cnt variable by 1.

  • For each adjoining vertex (neighbour) of B:

  • If the neighbour hasn't gone by and hasn't risen to vertex A, recursively call the DFS work on the neighbour.

  • After the DFS from vertex B is total, store the value of cnt in another variable (count 2).

  • Calculate the result by duplicating count1 by count2.

  • Output the result given the number of sets such that the path between each combination contains vertices A and B.

Example

#include <iostream>
#include <vector>
using namespace std;

int num_vertices, num_edges, a, b;

// Function to perform DFS on the given graph
// starting from the vertex 'start'
int performDFS(int start, int target, vector<int> graph[], vector<bool>& visited)
{
    visited[start] = true;
    int count = 1;

    // Perform DFS on the adjacent vertices
    for (auto adjacent : graph[start]) {
        if (!visited[adjacent] && adjacent != target)
            count += performDFS(adjacent, target, graph, visited);
    }

    return count;
}

// Function to calculate the number of pairs
// such that the path between any two pairs
// contains the given two vertices A and B
int calculatePairs(vector<int> graph[])
{
    vector<bool> visited(num_vertices + 1, false);

    int count_a = performDFS(a, b, graph, visited);
    visited.assign(num_vertices + 1, false);
    int count_b = performDFS(b, a, graph, visited);

    int ans1 = num_vertices - count_a - 1;
    int ans2 = num_vertices - count_b - 1;

    return ans1 * ans2;
}

int 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> graph[num_vertices + 1];

    // Loop to create the graph
    for (int i = 0; i < num_edges; i++) {
        graph[edges[i][0]].push_back(edges[i][1]);
        graph[edges[i][1]].push_back(edges[i][0]);
    }

    int result = calculatePairs(graph);

    cout << "Number of pairs such that the path between each pair contains the vertices " << a << " and " << b << ": " << result << endl;

    return 0;
}

Output

Number of pairs such that the path between each pair contains the vertices 3 and 5: 4

BFS

Within the Breadth−first−look (BFS) approach, we investigate a chart by going to vertices in a breadth−wise way. Beginning from a given source vertex, we visit all its neighbours, some time recently moving to the next level of neighbours. We keep up a line to keep track of the vertices to be gone to. As we visit each vertex, we stamp it as gone by to avoid returning to it. BFS makes a difference in finding the most limited way between two vertices and is broadly utilised for chart traversal and path−finding issues. It ensures that vertices are separated from the source by expanding their arrangement.

Algorithm

  • Make a purge line and a gone−by array.

  • Enqueue the source vertex into the line and check it as visited.

  • While the line isn't purgeable, do the following:

  • Dequeue a vertex from the front of the queue.

  • Process the dequeued vertex (e.g., print it or perform craved operations).

  • Enqueue all its unvisited neighbours into the line and stamp them as visited.

  • Repeat step 3 until the line is empty.

  • If there are still unvisited vertices, go back to step 2 and select another unvisited vertex as the source.

  • Terminate the calculation when all vertices have been reached.

Example

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

void bfs(vector<vector<int>>& graph, int source) {
    int n = graph.size();
    vector<bool> visited(n, false);

    queue<int> q;
    q.push(source);
    visited[source] = true;

    while (!q.empty()) {
        int vertex = q.front();
        q.pop();
        cout << vertex << " ";  // Process the visited vertex (e.g., print it)

        for (int neighbor : graph[vertex]) {
            if (!visited[neighbor]) {
                q.push(neighbor);
                visited[neighbor] = true;
            }
        }
    }
}

int main() {
    int numVertices = 6;
    vector<vector<int>> adjacencyList(numVertices);

    // Build the graph
    adjacencyList[0] = {1, 2};
    adjacencyList[1] = {3, 4};
    adjacencyList[2] = {4, 5};
    adjacencyList[3] = {5};
    adjacencyList[4] = {};
    adjacencyList[5] = {};

    int source = 0;

    bfs(adjacencyList, source);

    return 0;
}

Output

0 1 2 3 4 5 

Conclusion

This article clarifies two approaches, Depth−First Look (DFS) and Breadth−First Look (BFS), to discovering the number of sets in a chart such that the way between each match contains two indicated vertices, A and B. The DFS approach performs two isolated DFS traversals, expelling either vertex A or B, to tally the number of vertices that can still be reached. The BFS approach investigates the chart level by level, beginning from a given source vertex, to discover the most limited way and visit all reachable vertices. Both approaches give productive ways to analyse the chart and calculate the required sets based on the given condition.

Updated on: 14-Jul-2023

46 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements