![](/img/trans.png)
[英]Topological sort for directed graph made of two-dimensional vestor using DFS
[英]Optimization on Algorithm to check “Whether for a given directed graph there is only one way to sort the graph using topological sort or not”
我的算法是:
这是我对我的想法的实现
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.
}
这个算法太慢了! 或者只是一个天真的实施。 为此可以进一步改进。 或者我如何使用DFS对此进行拓扑排序?
定理:
有向图具有唯一的拓扑排序,当且仅当它是有向链时。
证据留给你作为锻炼
要确定有向图是否具有唯一的拓扑排序,您所要做的就是:
您的代码似乎没有遵循这种简单的方法。 (如果我错了,请纠正我!)因此,我建议只使用上面的算法大纲,而不是试图弄清楚你的代码是否正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.