
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program for Detect Cycle in a Directed Graph
A cycle occurs when a path starts and ends at the same vertex, following the direction of the edges. In directed graphs, cycles can cause problems like infinite loops or dependency errors, so detecting them is important in areas like task scheduling and deadlock detection.
We can use Depth-First Search (DFS) with a recursion stack to detect whether a cycle exists in a directed graph or not.
Problem Statement
You are given a directed graph represented using an adjacency list. Your task is to write a Python program to check whether the graph contains a cycle or not.
DFS-Based Cycle Detection
We use Depth-First Search (DFS) traversal and keep track of the nodes in the current recursion path. If we visit a node that is already in the recursion stack, it means a cycle exists.
Steps for DFS Cycle Detection
- Create a visited list to keep track of visited nodes.
- Use another list (recursion stack) to track the path of the current DFS.
- If a node is visited again while it is still in the recursion stack, a cycle is present.
- If all nodes are checked and no cycle is found, return False.
Python Program for Detecting a Cycle in a Directed Graph
In this example, we build a graph using an adjacency list and check for cycles using DFS and a recursion stack -
# Function to detect cycle in a directed graph using DFS def is_cyclic_util(v, visited, rec_stack, graph): visited[v] = True rec_stack[v] = True # Recur for all neighbours for neighbour in graph[v]: if not visited[neighbour]: if is_cyclic_util(neighbour, visited, rec_stack, graph): return True elif rec_stack[neighbour]: return True # Remove the vertex from recursion stack rec_stack[v] = False return False def is_cyclic(graph, V): visited = [False] * V rec_stack = [False] * V for node in range(V): if not visited[node]: if is_cyclic_util(node, visited, rec_stack, graph): return True return False # Test input: directed graph with a cycle V = 4 graph = [[] for _ in range(V)] graph[0].append(1) graph[1].append(2) graph[2].append(3) graph[3].append(1) # Cycle here print(is_cyclic(graph, V))
Following is the output obtained -
True
The function returns True because a cycle exists in the graph through vertices 1 -> 2 -> 3 -> 1.