This article describes using a depth-first search to sort the topology of a acyclic graph (DAG).
For a g= graph (v,e), its topological ordering is a linear order of all the nodes in G, which satisfies the following conditions: If G contains an edge (U,V) then the node U is in front of node V in the topological order (if the figure G contains a loop it is impossible to discharge a linear order). The topological ordering in the diagram can be seen as having all the nodes of the graph lined up on a horizontal line, with all edges pointing from left to right.
Give a topology diagram as follows:
The topology sorting algorithm is similar to DFS, but in the process of topological sequencing, each node is placed in a stack after the node in its adjacent link.
The specific code is as follows:
1#include <iostream>2#include <list>3#include <stack>4 using namespacestd;5 6 //the graph in the topological order should be a direction-free graph .7 classdag{8 Private:9 intv;Tenlist<int> *adj; One voidTopologicalsortutil (intVBOOL*visited,stack<int>&Stack); A Public: -DAG (intV);//ctor - voidAddedge (intStartintEnd);//a directed graph in a DAG the voidTopologicalsort (); - }; - -DAG::D AG (intv) { + This->v =v; -Adj =Newlist<int>[v]; + } A at voidDag::addedge (intStartintend) { - adj[start].push_back (end); - } - - voidDag::topologicalsortutil (intVBOOL* visited,stack<int>&Stack) { -VISITED[V] =true; in -list<int>::iterator Beg =Adj[v].begin (); to for(; Beg! = Adj[v].end (); + +Beg) + if(Visited[*beg] = =false) -Topologicalsortutil (*beg,visited,stack); the Stack.push (v); * } $ Panax Notoginseng voidDag::topologicalsort () { -stack<int> Stack = stack<int>(); the BOOL*visited =New BOOL[v]; + for(intI=0; i<v;i++) AVisited[i] =false; the + //recursive call tsutil function to store Topoligicalsort - // one by one $ for(intI=0; i<v;i++) $ if(Visited[i] = =false) - Topologicalsortutil (i,visited,stack); - the while(!Stack.empty ()) { -Cout<<stack.top () <<" ";Wuyi Stack.pop (); the } - } Wu - intMain () { AboutDag dag = dag (9); $Dag.addedge (1,6); -Dag.addedge (2,3); -Dag.addedge (3,6); -Dag.addedge (4,0); ADag.addedge (4,1); +Dag.addedge (5,2); theDag.addedge (5,0); -Dag.addedge (5,1); $Dag.addedge (7,8); the thecout<<"topological Sort of the given Directed acyclic Graph (DAG):"<<Endl; the Dag.topologicalsort (); thecout<<Endl; - in return 0; the}
The result of the operation is:
Literature Citation: An Introduction to algorithms->22.4 topological ordering
Code reference: http://www.geeksforgeeks.org/topological-sorting/
Graph of Algorithm series--Sort topology