Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains three cycles 0->2->0, 0->1->2->0 and 3->3, so your function must return true.
Depth First Traversal can be used to detect a cycle in a Graph. DFS for a connected graph produces a tree. There is a cycle in a graph only if there is a back edge present in the graph. A back edge is an edge that is from a node to itself (self-loop) or one of its ancestor in the tree produced by DFS. In the following graph, there are 3 back edges, marked with a cross sign. We can observe that these 3 back edges indicate 3 cycles present in the graph.
For a disconnected graph, we get the DFS forest as output. To detect cycle, we can check for a cycle in individual trees by checking back edges.
To detect a back edge, we can keep track of vertices currently in recursion stack of function for DFS traversal. If we reach a vertex that is already in the recursion stack, then there is a cycle in the tree. The edge that connects current vertex to the vertex in the recursion stack is a back edge. We have used recStack array to keep track of vertices in the recursion stack.
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
Graph contains cycle
Time Complexity of this method is same as time complexity of DFS traversal which is O(V+E).
In the below article, another O(V + E) method is discussed :
Detect Cycle in a direct graph using colors
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Detect Cycle in a Directed Graph using BFS
- Detect Cycle in a directed graph using colors
- Detect cycle in the graph using degrees of nodes of graph
- Detect cycle in an undirected graph using BFS
- Detect cycle in an undirected graph
- Detect a negative cycle in a Graph | (Bellman Ford)
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Hierholzer's Algorithm for directed graph
- Euler Circuit in a Directed Graph
- Check if a directed graph is connected or not
- Clone a Directed Acyclic Graph
- Convert Directed Graph into a Tree
- Longest Path in a Directed Acyclic Graph | Set 2
- Shortest Path in Directed Acyclic Graph