我对拓扑排序的步骤感到困惑,我发现 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 的反向?