Strongly Connected Components (Kosaraju's Algo) | Practice | GeeksforGeeks

Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, Find the number of strongly connected components in the graph.
 
Example 1:
Input:

Output:
3
Explanation:

We can clearly see that there are 3 Strongly
Connected Components in the Graph

Example 2:
Input:

Output:
1
Explanation:
All of the nodes are connected to each other.
So, there's only one SCC.

 
Your Task:
You don't need to read input or print anything. Your task is to complete the function kosaraju() which takes the number of vertices V and adjacency list of the graph as inputs and returns an integer denoting the number of strongly connected components in the given graph.
 
Expected Time Complexity: O(V+E).
Expected Auxiliary Space: O(V).
 
Constraints:
1  ≤  V  ≤  5000
0  ≤  E  ≤  (V*(V-1))
0  ≤  u, v  ≤  N-1
Sum of E over all testcases will not exceed 25*106
+1
patildhiren443 weeks ago
JAVA - 1.7
void topo(ArrayList<ArrayList<Integer>> adj, int node , Stack<Integer> st, boolean[]visit){
        visit[node] = true;
        
        for(int it : adj.get(node)){
            if(visit[it]==false){
                topo(adj, it, st, visit);
            }
        }
        st.push(node);
    }
    
    void revDfs(ArrayList<ArrayList<Integer>> adj, int node , boolean[]visit){
        visit[node] = true;
        
        for(int it : adj.get(node)){
            if(visit[it]==false){
                revDfs(adj, it, visit);
            }
        }
    }
    
    public int kosaraju(int vertex, ArrayList<ArrayList<Integer>> adj)
    {
        //code here
        Stack<Integer> st = new Stack<>();
        boolean[]visit = new boolean[vertex];
        
        for(int i=0; i<vertex; i++){
            if(visit[i]==false){
                topo(adj, i, st, visit);
            }
        }
        
        ArrayList<ArrayList<Integer>> transpose = new ArrayList<>();
        
        for(int i=0; i<vertex; i++){
            transpose.add(new ArrayList<>());
        }
        
        for(int i=0; i<vertex; i++){
            visit[i]=false;
            for(int it : adj.get(i)){
                transpose.get(it).add(i);
            }
        }
        
        int cou=0;
        while(!st.isEmpty()){
            int node = st.pop();
            
            if(visit[node]==false){
                cou++;
                revDfs(transpose, node, visit);
            }
        }
        return cou;
    }
+1
milindprajapatmst193 weeks ago
0.2/1.6
class Solution {
public:
    stack<int> S;
	bool visited[5000];
	vector<int> reversed_edges[5000];
	void dfs(int u, vector<int> edges[], bool push) {
	    visited[u] = true;
	    for (int& v : edges[u]) {
	        if (visited[v] == false)
	            dfs(v, edges, push);
	    }
	    if (push)
	        S.push(u);
	}
    int kosaraju(int n, vector<int> edges[]) {
        int cnt = 0;
        for (int u = 0; u < n; u++) {
            for (int& v : edges[u])
                reversed_edges[v].push_back(u);
        }
        memset(visited, false, sizeof(visited));
        for (int u = 0; u < n; u++) {
            if (visited[u] == false)
                dfs(u, edges, true);
        }
        memset(visited, false, sizeof(visited));
        while (!S.empty()) {
            int u = S.top();
            S.pop();
            if (visited[u] == false) {
                cnt++;
                dfs(u, reversed_edges, false);
            }
        }
        return cnt;
    }
};
0
saurabhsathe12341 month ago
C++ : 0.2
 
void TopoDFS(int V, vector<int> adj[] , vector<bool> &visited , stack <int> &s , int u)
	{
	    visited[u] = true;
	    for(auto v: adj[u])
	    {
	        if(!visited[v])
	           TopoDFS(V,adj,visited,s,v); 
	    }
	    s.push(u);
	}
	
    int kosaraju(int V, vector<int> adj[])
    {
        vector <bool> visited (V, false);
        stack<int> s ;
        for(int i=0; i<V ;i++)
        {
            if(!visited[i])
            {
                TopoDFS(V,adj,visited,s,i);
            }
                
        }
        
        vector <int> revAdj [V] ;
        for(int i=0;i<V;i++)
        {
            for(auto j : adj[i])
            {
                revAdj[j].push_back(i);
                //cout<< j <<" " << i << endl;
            }
        }
        
        fill(visited.begin(),visited.end(),false);
        stack<int> temp;
        int count;
        while(!s.empty())
        {
            int u = s.top();
            s.pop();
            if(!visited[u])
            {
                TopoDFS(V,revAdj,visited,temp,u);
                count++;
            }
        }
        return count;
    }
 
0
rohitshinde1803011 month ago
class Solution{public:void dfs(int node, stack<int> &st, vector<int> &vis, vector<int> adj[]){       vis[node] = 1;        for(auto it: adj[node]) {           if(!vis[it]) {              dfs(it, st, vis, adj);            }       }       st.push(node);    }
  void revDfs(int node, vector<int> &vis, vector<int> transpose[]){       vis[node] = 1;        for(auto it: transpose[node]) {           if(!vis[it]) {              revDfs(it, vis, transpose);            }       }   }   //Function to find number of strongly connected components in the graph.   int kosaraju(int n, vector<int> adj[]){       //code here       stack<int> st;      vector<int> vis(n, 0);      for(int i=0;i<n;i++) {        if(!vis[i]) {           dfs(i, st, vis, adj);         }    }     vector<int> transpose[n];     for(int i=0;i<n;i++) {        vis[i] = 0;         for(auto it: adj[i]) {           transpose[it].push_back(i);         }    }    int  components=0;    while(!st.empty()){        int node = st.top();        st.pop();         if(!vis[node]){           components++;           revDfs(node, vis, transpose);        }     }    return  components;   }}; 
0
gulshansahu1 month ago
// Java Solution 
public int kosaraju(int v, ArrayList<ArrayList<Integer>> adj)
    {
        //code here
        boolean visited[] = new boolean[v];
        Stack<Integer> st = new Stack<>();
        ArrayList<ArrayList<Integer>> ad = new ArrayList<ArrayList<Integer>>();
        
        for (int i=0; i<v; i++) {
            ad.add(new ArrayList<Integer>());
        }
        
        for (int i = 0; i<v; i++) {
            if (visited[i]== false) {
                dfs(ad, adj, i, visited, st);
            }
        }
       visited = new boolean[v];
       int count = 0;
        while (!st.isEmpty()) {
            int x = st.pop();
            if (visited[x] == false) {
                dfs2(ad, x, visited);
                count++;
            }
        }
        return count;
    }
    
    public void dfs2 (ArrayList<ArrayList<Integer>> adj, int i, boolean[] visited ) {
        if (visited[i] == false) {
            visited[i] = true;
            for (Integer x: adj.get(i)) {
                dfs2(adj, x, visited);
            }
        }
    }
    
    public void dfs (ArrayList<ArrayList<Integer>> ad, ArrayList<ArrayList<Integer>> adj, int i, boolean[] visited, Stack<Integer> st) {
        if (visited[i] == false) {
            visited[i] = true;
            for (Integer x : adj.get(i)) {
                ad.get(x).add(i);
                dfs(ad, adj, x, visited, st);
            }
            st.push(i);
        }
        
    }
0
raunakmishra12431 month ago
int kosaraju(int V, vector<int> adj[])
    {
        vector<int>vis(V,0);
        stack<int>s;
        for(int i=0;i<V;i++)
        {
            if(!vis[i])
            {
                dfs(i,s,vis,adj);
            }
        }
        vector<int>transpose[V];
        for(int i=0;i<V;i++)
        {
            vis[i]=0;
            for(auto it :adj[i])
            transpose[it].push_back(i); 
        }
        int c=0;
        
        while(!s.empty())
        {
            
            int node=s.top();
            s.pop();
            if(!vis[node])
            {    c++;
                revof(node,vis,transpose);
                
            }
        }
        return c;
    }
    void dfs(int node,stack<int>&s,vector<int>&vis,vector<int> adj[])
	{
	    vis[node]=1;
	    
	    for(auto it:adj[node])
	    {
	        if(!vis[it])
	        {
	            dfs(it,s,vis,adj);
	        }
	        
	    }
	    s.push(node);
	}
   void revof(int node,vector<int>&vis,vector<int>tra[])
   {
       vis[node]=1;
       for(auto it:tra[node])
       {
           if(!vis[it])
           revof(it,vis,tra);
       }
   }
+1
himanshukug19cs2 months ago
java solution
boolean[] vis;   void sol(int v,ArrayList<ArrayList<Integer>> adj,Stack<Integer> st){       vis[v]=true;       for(int i:adj.get(v)){           if(vis[i]==false)               sol(i,adj,st);       }       st.push(v);   }    void scg(int v,ArrayList<ArrayList<Integer>> al){       vis[v]=true;       for(int i:al.get(v)){           if(vis[i]==false)               scg(i,al);       }          }   public int kosaraju(int V, ArrayList<ArrayList<Integer>> adj)   {       //code here       vis= new boolean[V];          Stack<Integer> st = new Stack<>();       for(int i=0;i<V;i++){       if(vis[i]==false)                 sol(i,adj,st);       }       ArrayList<ArrayList<Integer>> al = new ArrayList<>();       for(int i=0;i<V;i++){           al.add(new ArrayList<>());       }          for(int i=0;i<V;i++){           vis[i]=false;       for(int j:adj.get(i)){           al.get(j).add(i);       }       }       int count=0;       while(!st.isEmpty()){           int j=st.pop();          if(vis[j]==false){              count++;              scg(j,al);                       }                   }       return count;   }
+1
harsh345682 months ago
Strivers Code with few Modifications
 
void dfs(int node,stack<int>&st,vector<int>&vis,vector<int>adj[],int v)   {       vis[node]=1;       for(auto it:adj[node])       {           if(!vis[it])               dfs(it,st,vis,adj,v);       }       st.push(node);   }      void revdfs(int node,vector<int>&vis,vector<int>adj[],int v)   {   vis[node]=1;       for(auto it :adj[node])       if(!vis[it])revdfs(it,vis,adj,v);   }   int kosaraju(int V, vector<int> adj[])   {       //code here       stack<int>st;       vector<int>vis(V,0);       for(int i=0;i<V;i++)       {if(!vis[i]) dfs(i,st,vis,adj,V);       }       vector<int>transpose[V];       for(int i=0;i<V;i++){           vis[i]=0;           for(auto it:adj[i])           {transpose[it].push_back(i);           } }       int ans=0;       while(!st.empty())       {int node=st.top();           st.pop();           if(!vis[node])             { revdfs(node,vis,transpose,V);             ans++;              } }       return ans;          }
0
harsh34568
This comment was deleted.
+1
siddhant072 months ago
//Kosaraju's Algorithm to find number of strongly connected components in a graph based on TopoSort
	void dfs(int V, vector<int> adj[], stack<int> &st, vector<bool> &visited, int i){
	    visited[i] = true;
	    for(auto &v : adj[i]){
	        if(visited[v] == false){
	            dfs(V, adj, st, visited, v);
	        }
	    }
	    st.push(i);
	}
	void dfs2(int V, vector<int> adj[], vector<bool> &visited, int i){
	    visited[i] = true;
	    for(auto &v : adj[i]){
	        if(visited[v] == false){
	            dfs2(V, adj,visited, v);
	        }
	    }
	}
    int kosaraju(int V, vector<int> adj[])
    {
        stack<int> st;
        vector<bool> visited (V, false);
        for(int i = 0; i < V; i++){
            if(visited[i] == false){
                dfs(V, adj, st, visited, i);
            }
        }
        vector<int> transpose[V];
        for(int i = 0;i < V; i++){
            visited[i] = false;
            for(auto &e : adj[i]){
                transpose[e].push_back(i);
            }
        }
        int cnt = 0;
        while(!st.empty()){
            int curr = st.top();
            if(visited[curr] == false){
                dfs2(V, transpose, visited, curr);
                cnt++;
            }
            st.pop();
        }
        return cnt;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.