CLRS拓扑排序算法与DFS相反?

时间:2013-06-13 20:53:34

标签: c++ graph

我有一个混淆看着拓扑排序的步骤,我看到DFS的相反顺序是拓扑排序的预期解决方案。

我还尝试了一个小代码

void graph::dfs(void)
{
    for(std::vector<vertex>::iterator iter =vertexes.begin();iter < vertexes.end();iter++ ){
        iter->visited = WHITE;  
    }   

    for(std::vector<vertex>::iterator iter =vertexes.begin();iter < vertexes.end();iter++ ){
        if(iter->visited == WHITE){
            dfs_visits(*iter);
        }
    }

    std::cout << "-----------------dfs------------------"<<std::endl;
    for(std::list<int>::reverse_iterator riter = q.rbegin() ; riter != q.rend();riter++)
        std::cout << *riter << std::endl;

    std::cout << "-----------------topological_sort------------------"<<std::endl;
    for(std::list<int>::iterator iter = q.begin() ; iter != q.end();iter++)
        std::cout << *iter << std::endl;


    q.clear();
}


void graph::dfs_visits(vertex& source){
    source.visited = GREY;
    for(std::list<edge>::iterator iter = source.list.begin();iter != source.list.end();iter++){
        if(vertexes[iter->destination_vertex].visited == WHITE){
            dfs_visits(vertexes[iter->destination_vertex]);
        }
    }
    source.visited = BLACK;
    q.push_front(source.id);
}

图形数据结构在这里

#include "iostream"
#include "vector"
#include "list"

enum color{
    WHITE,
    GREY,
    BLACK
};

struct edge{
    int destination_vertex;
    edge(int ver){
        destination_vertex = ver;
    }
};

struct vertex{
    int id;
    color visited;
    std::list<edge>  list;
    vertex(int _id){
        id = _id;
    }
};


class graph
{
private:
    std::vector<vertex> vertexes;
    int next;
    std::list<int> q;
public:
    graph(void){
        next = 0;
    }
    ~graph(void){}
    void add_node(std::vector<int> edges );
    void add_node(std::vector<int> incoming_edges , std::vector<int> outgoing_edges);
    void print();
    void dfs();
    void dfs_visits(vertex& source);
    void bfs();
    static void process();
};

这是一个例如我试过的图表

0->1,2,
1->3,
2->
3->
4->
5->4,
-----------------dfs------------------
3
1
2
0
4
5
-----------------topological_sort-----
5
4
0
2
1
3
改变问题陈述

我的问题很简单..拓扑排序是否总是DFS反向排序?如果不存在反例?

如果你看到特定图形的输出,DFS输出及其反转也是图形拓扑排序的正确解决方案....也读取CLR拓扑排序算法它看起来像拓扑排序是相反的DFS?

1 个答案:

答案 0 :(得分:2)

是的,它总是如此。 DAG上DFS的反向给出了拓扑排序。

来源:http://www.cse.ust.hk/faculty/golin/COMP271Sp03/Notes/MyL08.pdf幻灯片13