This post is completed by 1 user

  • 1
Add to List

273. Graph – Detect Cycle in a Directed Graph

Objective: Given a directed graph write an algorithm to find out whether graph contains cycle or not.



Graph contains cycle if there are any back edges. There are two types of back edges as seen in the example above (marked in red)

  1. Edge from a vertex to itself. Self loop. (4-4)
  2. Edge from any descendent back to vertex.

Use DFS(Depth-First Search) to detect the back edge

  1. Do the DFS from each vertex
  2. For DFS from each vertex, keep track of visiting vertices in a recursion stack (array).
  3. If you encounter a vertex which already present in recursion stack then we have found a cycle.
  4. Use visited[] for DFS to keep track of already visited vertices.

How different is recursion stack[] from visitied [].

  1. Visited[] is used to keep track of already visited vertices during the DFS is never gets
  2. Recursion stack[] is used from keep track of visiting vertices during DFS from particular vertex and gets reset once cycle is not found from that vertex and will try DFS from other vertices.
  3. See the code from more understanding.

Time Complexity: O(V+E)


is Cycle present: True