My algorithm for this is :
Here is My implementation of my Idea
vector<vector<int> >list(10000); // Graph is represented as Adjacency list
void topological_sort()
{
int i,l,item,j;
k=0;
queue<int>q; // Queue
vector<int>:: iterator it;
for(i=1;i<=n;i++) // Pushing nodes those who have indegree=0
{
if(indegree[i]==0)
q.push(i);
}
l=q.size();
if(l==0)
{
flag=2; // means no sequence is possible
return;
}
while(q.empty()==0)
{
l=q.size();
if(l>1)
flag=1; // multiple sequence possible for sure but check whether this is fully possible or not
item=q.front();
q.pop();
ans[k++]=item;
for(it=list[item].begin();it!=list[item].end();it++)
{
j=*it;
indegree[j]--;
if(indegree[j]==0)
q.push(j);
}
}
if(k!=n)
flag=2; // no sequence is possible.
}
This algorithm is too slow! or just a naive implementation. What further Improvements are possible for this. or how can i use toplogical sort using DFS for this ?
Theorem:
A directed graph has a unique topological sort if and only if it is a directed chain.
Proof left as exercise for you
To determine if a directed graph has a unique topological sort, all you have to do is:
Your code doesn't seem to follow this simple approach. (Correct me if I'm wrong about that!) So, rather than trying to figure out if your code is correct or not, I would suggest simply using the algorithm outline above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.