在有向无环图中,我们可以使用拓扑排序以线性顺序对顶点进行排序。
拓扑排序仅适用于有向无环图。在有向无环图(DAG)中,可以有多个拓扑类别。
在下面的C ++程序中,我们将执行拓扑排序以检查图中是否存在循环。
Begin Define function Topo_Sort() Declare x to the integer datatype, vstd[] of the Boolean array and Stack as a stack. Pass them as parameter. Initialize vstd[x] = true to mark the current node as vstd. Declare an iterator i. for (i = a[x].begin(); i != a[x].end(); ++i) if (!vstd[*i]) then Call Topo_Sort(*i, vstd, Stack) function. Call push() function to insert values into stack. End.
#include<iostream> #include <list> #include <stack> using namespace std; class grph { // Class to represent a graph int ver; list<int> *a; // Pointer to an array containing adjacency listsList void Topo_Sort(int x, bool vstd[], stack<int> &Stack); // A function used by TopologicalSort public: grph(int ver); // Constructor of grpf void Insert_Edge(int x, int y); // to insert an edge to graph void Topol_Sort(); // prints a Topological Sort of the complete graph }; grph::grph(int ver) { this->ver = ver; a = new list<int>[ver]; } void grph::Insert_Edge(int x, int y) { a[x].push_back(y); // Add y to x’s list. } //使用的递归函数 void grph::Topo_Sort(int x, bool vstd[], stack<int> &Stack) { vstd[x] = true; // Mark the current node as vstd. list<int>::iterator i; for (i = a[x].begin(); i != a[x].end(); ++i) if (!vstd[*i]) Topo_Sort(*i, vstd, Stack); //将当前顶点推入堆栈以存储结果 Stack.push(x); } void grph::Topol_Sort() { stack<int> Stack; //将所有顶点标记为非vstd- bool *vstd = new bool[ver]; for (int i = 0; i < ver; i++) vstd[i] = false; for (int i = 0; i < ver; i++) if (vstd[i] == false) Topo_Sort(i, vstd, Stack); while (Stack.empty() == false) { cout << Stack.top() << " "; Stack.pop(); } } int main() { grph g(6); // Create a graph given in the above diagram g.Insert_Edge(5, 2); g.Insert_Edge(5, 0); g.Insert_Edge(4, 0); g.Insert_Edge(4, 1); g.Insert_Edge(2, 3); g.Insert_Edge(3, 1); cout << "Topological Sort of the graph is: \n"; g.Topol_Sort(); return 0; }
输出结果
Topological Sort of the graph is: 5 4 2 3 1 0