Detect cycle in a Directed Graph
To determine whether a graph has a ring, see the following:
The only note here is that this is a directed graph, and the edges form a ring, which is not necessarily a ring, because the direction can be inconsistent.
Here we add an array to save the path information recstack [] that has already been asked by the queue.
The visited [] array is the information of vertices that have been asked by the observer. The functions of the two are different.
Knowing this knowledge point makes this question very easy.
Original article:
Http://www.geeksforgeeks.org/detect-cycle-in-a-graph/
# Include <stdio. h> # include <list> # include <limits. h ># include <iostream> using namespace STD; Class detectcycleinadirectedgraph {int size; List <int> * adj; bool iscycleutil (int v, bool visited [], bool * recstack) {If (! Visited [v]) {// clever question: Add recstack, because it is directed, if it is undirected, then we don't really need recstack. visited [v] = recstack [v] = true; List <int >:: iterator it = adj [v]. begin (); For (; it! = Adj [v]. End (); It ++) {If (! Visited [* It] & iscycleutil (* It, visited, recstack) return true; else if (recstack [* It]) return true ;} recstack [v] = false;} return false;} public: detectcycleinadirectedgraph (int v): size (v) {adj = new list <int> [size];} void addedge (int v, int W) {adj [v]. push_back (w);} bool iscyclic () {bool * visited = new bool [size]; bool * recstack = new bool [size]; fill (visited, visited + size, false); fill (recstack, recstack + size, false); For (INT I = 0; I <size; I ++) {If (iscycleutil (I, visited, recstack) return true;} return false;}; void detectcycleinadirectedgraph_run () {detectcycleinadirectedgraph g (4); G. addedge (0, 1); G. addedge (0, 2); G. addedge (1, 2); G. addedge (2, 0); G. addedge (2, 3); G. addedge (3, 3); If (G. iscyclic () cout <"graph contains cycle \ n"; elsecout <"graph doesn't contain cycle \ n ";}
Geeks-detect cycle in a Directed Graph