Answers for "topological sorting in c++"

C++
4

topological sort cp algorithms

int n; // number of vertices
vector<vector<int>> adj; // adjacency list of graph
vector<bool> visited;
vector<int> ans;

void dfs(int v) {
    visited[v] = true;
    for (int u : adj[v]) {
        if (!visited[u])
            dfs(u);
    }
    ans.push_back(v);
}

void topological_sort() {
    visited.assign(n, false);
    ans.clear();
    for (int i = 0; i < n; ++i) {
        if (!visited[i])
            dfs(i);
    }
    reverse(ans.begin(), ans.end());
}
Posted by: Guest on August-24-2020
0

topological sort c++

//Topological sort DFS
//Complete code 
//Possible Only on DAG(Directed Acyclic Graph)
#include<bits/stdc++.h>
using namespace std;
void addedge(vector<int>adj[],int u,int v)
{
    adj[u].push_back(v);

}
void topo(int val,stack<int>&st,vector<int>adj[],vector<int>&visited)
{
    visited[val]=1;
    for(auto i:adj[val])
    {
        if(!visited[i])
        {
            topo(i,st,adj,visited);
        }
    }
    st.push(val);
}
void toposort(vector<int>adj[],int n)
{
    stack<int>st;
    vector<int>visited(n,0);
    for(int i=0;i<n;i++)
    {
        if(visited[i]==0)
        {
            topo(i,st,adj,visited);
        }
    }
    vector<int>topo;
    while(!st.empty())
    {
        topo.push_back(st.top());
        st.pop();
    }
    int s=topo.size();
    for(int j=0;j<s;j++)
    {
        cout<<topo[j]<<" ";
    }
}
int main()
{
    int vertex,edges;
    cout<<"Enter the vertex and edges"<<endl;
    cin>>vertex>>edges;
    vector<int>adj[vertex];
    int a,b;
    cout<<"Enter the links"<<endl;
    for(int i=0;i<vertex;i++)
    {
        cin>>a>>b;
        addedge(adj,a,b);
    }
    toposort(adj,vertex);
    return 0;
}
Posted by: Guest on August-16-2021

Browse Popular Code Answers by Language