Topological Sort:
1. 什么是拓扑排序
拓扑排序是对有向无环图 DAG 中的所有节点的一种线性次序,满足如下条件:对于每一条有向边 uv,拓扑排序中,节点 u 总会出现在节点 v 之前,拓扑排序只能用于 DAG
例如{5,4,2,3,1,0}就是一种拓扑排序,当然拓扑排序也不是唯一,{4,5,2,3,1,0}也是一种拓扑排序。
2. 拓扑排序与 DFS 遍历的区别
与拓扑排序不同,DFS 的结果为{5,2,3,1,0,4}
3. 拓扑排序的实现
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <stack>
#include <list>
using namespace std;
class Graph {
// the number of vertices
int V;
// contain adjacency vertices
list<int>* adj;
// A function used by TopologicalSort
void TopologicalOrder(int v,bool isvisited[],stack<int>& Stack);
public:
// Constructor
Graph(int V);
// A function to add an edge to graph
void addEdge(int v,int w);
// A TopologicalSort of DAG
void TopologicalSort();
};
Graph:: Graph(int v)
{
this->V = v;
adj = new list<int>[v];
}
void Graph::addEdge(int v,int u)
{
adj[v].push_back(u);
}
void Graph::TopologicalOrder(int v,bool isvisited[],
stack<int>& Stack)
{
// Mark the current nodes as visited
isvisited[v] = true;
// Recur for all the vertices
// adjacent to this vertex
list<int>::iterator iter;
for(iter = adj[v].begin();iter != adj[v].end();iter++)
if(!isvisited[*iter])
TopologicalOrder(*iter,isvisited,Stack);
// Push current vertex to stack
// which stores result
Stack.push(v);
}
// This function to do Topological Sort.
// It uses recursive TopologicalOrder()
void Graph::TopologicalSort()
{
stack<int>Stack;
// Mark all the vertices as not visited
bool isvisited[V];
for(int i = 0;i < V;i++)
isvisited[i] = false;
for(int i = 0;i < V;i++)
if(!isvisited[i])
TopologicalOrder(i,isvisited,Stack);
// Print contents of stack
while(!Stack.empty()) {
cout<< Stack.top()<<" ";
Stack.pop();
}
}
int main()
{
// Create a graph
Graph graph(6);
graph.addEdge(5,2);
graph.addEdge(5,0);
graph.addEdge(4,0);
graph.addEdge(4,1);
graph.addEdge(2,3);
graph.addEdge(3,1);
cout<<"Following is a Topological Sort of the given graph"<<endl;
graph.TopologicalSort();
return 0;
}