![](/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.