Given a graph with N nodes and M directed edges. Your task is to complete the function kosaraju() which returns an integer denoting the number of strongly connected components in the graph - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Thursday 18 June 2020

Given a graph with N nodes and M directed edges. Your task is to complete the function kosaraju() which returns an integer denoting the number of strongly connected components in the graph

Given a graph with N nodes and M directed edges. Your task is to complete the function Kosaraju() which returns an integer denoting the number of strongly connected components in the graph.

here is simple and easy approach solution using stack , dfs , vector matrice etc.

We can find all strongly connected components in O (V + E) time using Kosaraju's algorithm. Later Kosaraju's algorithm is detailed.
1) Create an empty stack 'S' and do a DFS traversal of a graph. In DFS traversal, after calling recursive DFS for an adjacent corner of a vertex, push the vertex to stack. In the above graph, if we start DFS from the top 0, we get verticals in the stack as 1, 2, 4, 3, 0.
2) Reverse instructions of all arcs to obtain transpose graphs.
3) One to one pop s from a  top while s is not empty. Allow the popup work to be tex v '. Take v as the source and do DFS (call DFSUtil (v)). The DFS starting from the V print is a strongly connected component of V. In the example above, we process in the order 0, 3, 4, 2, 1 (one by one popup from the stack).


Quote, Teal, Lavender, Saying, Motivational Quotes


void dfs(int s, vector < int > adj[], bool vis[]) {
    vis[s] = true;
    for (int x: adj[s])
        if (vis[x] == false)
            dfs(x, adj, vis);

}

void fillorder(int s1, vector < int > adj[], bool vis[], stack < int > & s) {
    vis[s1] = true;
    for (int x: adj[s1]) {
        if (vis[x] == false)
            fillorder(x, adj, vis, s);
    }
    s.push(s1);
}

int kosaraju(int V, vector < int > adj[]) {
    stack < int > s;
    bool vis[V];
    memset(vis, false, sizeof(vis));
    for (int i = 0; i < V; i++)
        if (vis[i] == false)
            fillorder(i, adj, vis, s);
    memset(vis, false, sizeof(vis));
    vector < int > adj1[V];
    for (int i = 0; i < V; i++) {
        for (int x: adj[i])
            adj1[x].push_back(i);
    }

    int c = 0;
    while (!s.empty()) {
        int u = s.top();
        s.pop();

        if (vis[u] == false) {
            dfs(u, adj1, vis);
            c++;
        }

    }
    return c;

}

// { Driver Code Starts.

int main() {
    int t;
    cin >> t;
    while (t--) {
        int a, b;
        cin >> a >> b;
        int m, n;
        vector < int > adj[a + 1];
        for (int i = 0; i < b; i++) {
            cin >> m >> n;
            adj[m].push_back(n);
        }
        // exit(0);
        cout << kosaraju(a, adj) << endl;
    }
    return 0;
} // } Driver Code Ends