This algorithm requires no Queue or Stack.
#include <bits/stdc++.h>
#define MAX 2000
using namespace std;
vector<int> topSort(int node, vector<int> &indeg, vector<vector<int> > &adj)
{
vector<int> ans;
for(int i=0; i<node; i++) //Inserting all independent nodes first
{
if(indeg[i]==0) ans.push_back(i);
}
for(int i=0; i<ans.size(); i++)
{
int u=ans[i];
for(int j=0; j<adj[u].size(); j++)
{
int v=adj[u][j];
indeg[v]--;
if(indeg[v]==0) ans.push_back(v);
}
}
if(ans.size()!=node) ans.clear(); //cycle found, so returning empty vector
return ans;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int node, edge;
cout<<"Enter the number of nodes and edges: ";
while(cin>>node>>edge) //assuming node>=0, edges>=0
{
vector<int> indeg(node,0);
vector<vector<int> > adj(node);
/* //for string input
unordered_map<string,int> mp;
unordered_map<int,string> mp;
int c=0;
*/
if(edge==0) //Print all nodes as all are independent
{
for(int i=0; i<node; i++) cout<<i<<" ";
cout<<endl;
}
cout<<"Enter the relations(pair of edges): "<<endl;
for(int i=0; i<edge; i++) //Populating Adjacency list and indeg array for TopSort
{
int from,to;
//string from,to;
cin>>from>>to;
/* //Processing string input
if(mp1[from]==0)
{
mp1[from]=++c;
mp2[c]=from;
}
if(mp1[to]==0)
{
mp1[to]=++c;
mp2[c]=to;
}
g[mp1[from]].pb(mp1[to]);
indeg[mp1[to]]++;
*/
adj[from].push_back(to);
indeg[to]++;
}
vector<int> ans=topSort(node, indeg, adj);
if(ans.size()>0) //Ordering possible
{
cout<<"The correct ordering is:";
for(int i=0; i<ans.size(); i++)
{
cout<<" "<<ans[i];
//cout<<mp2[ans[i]]<<" ";
}
cout<<endl;
}
else cout<<"Cycle exists"<<endl; //Ordering not possible
}
return 0;
}