Subscribe Us

Responsive Advertisement

Advertisement

Proble 17 : Topological Sort Algorithm using DFS|C++

  




#include<bits/stdc++.h>

using namespace std;

#define ll long long int

const ll N=1000;

stack<ll>st;

vector<ll>adj[N];

ll vis[N];

void dfs(ll node)

{

     vis[node]=1;

     for(ll i=0;i<adj[node].size();i++)

     {

         ll child;

         child=adj[node][i];

         if(vis[child]==0)

         {

             dfs(child);

         }

     }

     st.push(node);

}

int main()

{


    cout<<"Enter number node and edge : ";

    ll node,edge;

    cin>>node>>edge;

    while(edge--)

    {

        ll u,v;

        cin>>u>>v;

        adj[u].push_back(v);

       // adj[v].push_back(u);


    }

    for(ll i=0;i<node;i++)

    {

        if(vis[i]==0)

        {

            dfs(i);

        }

    }

    while(!st.empty())

    {

        cout<<st.top()<<" ";

        st.pop();

    }

}


Post a Comment

0 Comments