Graph traversal has depth-first and breadth-first algorithm.
Depth-first traversal can be described as a recursive algorithm. When the vertex v is reached, the specific operation is:
① access (v);
②for (w) for each vertex (W) adjacent to V;
Depth-First algorithm template<int max_size>void diagraph<max_size>::d epth_first (void (*visit) (Vertex &)) const { BOOL Visited[max_size]; The introduction of arrays prevents infinite loops vertex v;for (all v in g) visited[v] = False;for (all v in g) {if (!visited[v]) {traverse (V, visited, visit);} }}template<int max_size>void diagraph<max_size>::traverse (Vertex &v, bool Visited[],void (*visit) ( Vertex &)) const {Vertex W;visited[v] = true; (*visit) (v); for (all w adjacent to V) {if (!visited[w]) {traverse (W, Visi Ted, visit);}}}
The breadth-first algorithm uses a queue that, when accessed V, appends the remaining unreachable vertices of V to the queue, and then accesses the queue header:
Breadth-First algorithm template<int max_size>void diagraph<max_size>::breadth_first (void (*visit) (Vertex &)) const {Queue Q;bool visited[max_size]; Vertex V, W, x;for (all V in grams) visited[v] = False;for (all v in g) {if (!visited[v]) {q.append (v); while (!q.empty ()) {Q.R Etrieve (W), if (!visited[w]) {visited[w] = true; (*visit) (w); for (all x adjacent to W) {q.append (x);}} Q.serve ();}}}
You can use depth-first traversal and breadth-first traversal to determine the topological order.
Depth-First traversal: Time complexity O (n+e) (n is the fixed-point number of the graph, and E is the number of sides of the graph).
Depth-First algorithm template<int graph_size>void diagraph<graph_size>:: Depth_sort (list<vertex>& Topological_order) {bool Visited[graph_size]; Vertex v;for (v = 0; v < count; v++) Visited[v] = False;topological_order.clear (); for (v = 0; v < count; v++) {if (! Visited[v]) {Recursive_depth_sort (V, visited, Topological_order);}}} Template<int max_size>void Diagraph<max_size>::recursive_depth_sort (Vertex V, bool *visited, List< vertex>& topological_order) {visited[v] = True;int degree = neighbors[v].size (); for (int i = 0; i < degree; i++) {Vertex W;neighbors[v].retrieve (i, W), if (!visited[w]) {recursive_depth_sort (W, visited, Topological_order);}} Topological_order.insert (0, v);}
Depth first and breadth first algorithm