使用BGL(Boost图库)查找DAG中的所有拓扑排序

时间:2017-02-24 16:38:35

标签: c++ boost topological-sort

如何使用Boost Graph Library查找给定DAG G的所有拓扑排序?

我找到了一些理论参考来解释这是可能的,还有这个code,其中有一个实现。但我实际上并不想从头开始,我想用BGL来计算它们。

1 个答案:

答案 0 :(得分:0)

一种策略是获得没有前驱的所有顶点(没有前导边缘)。并且在没有前任的情况下基于顶点乘以向量。如果您有C ++,请分享。

获取depth_first拓扑排序的代码:

给定顶点类型为graph的DAG vertex_t

deque<vertex_t> topologicalSorted;

//perform topological sort
if (topologicalSort(graph, topologicalSorted)) {
    cout << "The graph is directed acyclic!" << endl;
    cout << "Topological order: ";
    for (int i = 0; i < topologicalSorted.size(); i++) {
        cout << graph[topologicalSorted.at(i)].label << " ";
    }
    cout << endl;
} 


bool topologicalSort()
{
    try
    {
        boost::topological_sort(graph, front_inserter(topologicalSorted));
    }
    catch (boost::not_a_dag)
    {
        cout << "not a dag\n";
        return false;
    }
    cout << "top sort OK\n";

    return true;
} 

没有自定义顶点:

deque<int> topologicalSorted;

if (topologicalSort()) {
        // Print the results.
        for (int i = 0; i < topologicalSorted.size(); i++) {
            cout << topologicalSorted.at(i) << ",";
        }
        cout << endl;
    }