Wednesday, 1 April 2026

SDE trajan's Algorithm (Detect and print Strongly connected components of a graph)

 // User function template for C++


class Solution {

  public:

    // Function to return a list of lists of integers denoting the members

    // of strongly connected components in the given graph.

    void DFS(int node,int &timer,vector<int>&dis,vector<int>&low,vector<bool>&visited,vector<bool>&isStack,stack<int>&st,vector<vector<int>>&ans,vector<int>adj[]){

        visited[node]=1;

        dis[node]=low[node]=timer;

        st.push(node);

        isStack[node]=1;

        timer=timer+1;

        for(int x:adj[node]){

            if(!visited[x]){

                DFS(x,timer,dis,low,visited,isStack,st,ans,adj);

                

                low[node]=min(low[node],low[x]);

                

            }else {

                if(isStack[x]){

                    low[node]=min(low[node],low[x]);

                }

            }

        }

        vector<int>temp;

        if(dis[node]==low[node]){

           

        while(st.top()!=node){

                temp.push_back(st.top());

                isStack[st.top()]=0;

                st.pop();

        }

        temp.push_back(st.top());

        st.pop();

        sort(temp.begin(),temp.end());

        ans.push_back(temp);

        isStack[node]=0;

        }

        

        

        

        

    }

    vector<vector<int>> tarjans(int V, vector<int> adj[]) {

        // code here

        stack<int>st;

        vector<bool>visited(V,0);

        vector<bool>isStack(V,0);

        vector<int>dis(V,-1);

        vector<int>low(V,-1);

        int timer=0;

        vector<vector<int>>ans;

        for(int i=0;i<V;i++){

            if(!visited[i]){

                DFS(i,timer,dis,low,visited,isStack,st,ans,adj);

            }

        }

        sort(ans.begin(),ans.end());

        return ans;

    }

};

No comments:

Post a Comment

SDE floyd-warshall algorithm

 // User function template for C++ class Solution {   public:     void floydWarshall(vector<vector<int>> &dist) {         //...