You are given a directed graph. Write a function to detect if it has a cycle. Please write a function that solves this problem using Depth First Search (DFS), explain your algorithm. You will need to keep track of the nodes currently in the recursion stack (visiting) in addition to the nodes that have been fully visited, what is the time complexity of your solution, and how would this problem be different for an undirected graph.
Assistant
We need to write a function that detects a cycle in a directed graph using DFS.
We will represent the graph as an adjacency list. The function will return True if there is a cycle, else False.
Algorithm:
We'll maintain two sets (or a list/dict for states):
visited: nodes that have been fully processed (all descendants visited)
rec_stack: nodes that are currently in the recursion stack of DFS (i.e., the current DFS path)
Steps:
For each node in the graph, if it hasn't been visited, start DFS from that node.
In DFS for a node u:
mark u as visited and add to rec_stack.
for each neighbor v of u:
if v is not visited, then recursively do DFS on v.
if during that recursion we find a cycle, return True.
else if v is in rec_stack (meaning v is already in the current DFS path), then we have found a cycle, return True.
after processing all neighbors, remove u from rec_stack (since we are backtracking) and return False.
If we finish DFS for all nodes without finding a cycle, return False.
Note: The graph might not be connected, so we need to iterate over all nodes.
Time Complexity: O(V + E) because each node and edge is visited once.
For an undirected graph:
In an undirected graph, a cycle is defined as a path of length at least 3 that starts and ends at the same node, and the edges are undirected.
In DFS for undirected graphs, we don't need the rec_stack to detect a cycle because if we visit a neighbor that is already visited and that neighbor is not the parent (the node we came from), then we have a cycle.
However, note that in an undirected graph, the condition is: if we find an adjacent node that is visited and not the parent, then cycle exists.
Also, note that in an undirected graph, we usually avoid considering the edge back to the parent as a cycle.
Implementation for directed graph:
Let's code accordingly.
To detect cycles in a directed graph using Depth First Search (DFS), we maintain two tracking mechanisms:
visited set: Nodes that have been fully processed (all descendants explored).
recursion_stack set: Nodes currently in the DFS recursion stack (the active path from the root to the current node).
Algorithm Explanation
For each unvisited node:
Mark it as visited and add to recursion_stack.
Recursively visit all its neighbors.
During recursion:
If a neighbor is unvisited, recursively DFS it.
If a neighbor is already in recursion_stack, a cycle is detected (back-edge to an ancestor in the current DFS path).
After exploring all neighbors, remove the node from recursion_stack (backtracking).
If no cycles found after processing all nodes, graph is acyclic.
python
def has_cycle_directed(graph):
"""
Detects cycle in directed graph using DFS.
:param graph: Dict[int, list[int]] - adjacency list representation
:return: bool - True if cycle exists, else False
"""
visited = set()
recursion_stack = set()
def dfs(node):
visited.add(node)
recursion_stack.add(node)
for neighbor in graph.get(node, []):
if neighbor not in visited:
if dfs(neighbor):
return True
elif neighbor in recursion_stack:
return True # Back-edge found (cycle)
recursion_stack.remove(node) # Backtrack
return False
for node in graph:
if node not in visited:
if dfs(node):
return True
return False
Time Complexity
O(V + E)
Each node (V) and edge (E) is visited exactly once. The recursion_stack and visited operations are O(1) average (using hash sets).
Comparison: Directed vs. Undirected Graph
Aspect
Directed Graph
Undirected Graph
Cycle detection
Use recursion_stack to detect back-edges (to any ancestor in current DFS path).
Track parent node; cycle if neighbor is visited and not parent (no need for separate recursion_stack).
Edge interpretation
Edge direction matters; u → v ≠ v → u. A back-edge (v → u) to an ancestor u indicates a cycle.
Edges are bidirectional; traversing u - v then v - u is trivial and not a cycle (unless avoiding immediate parent).
DFS modification
Requires explicit recursion_stack to distinguish** between cross-edges/forward-edges (allowed) and back-edges (cycle).
Only need visited set and parent tracking; no recursion_stack needed because any visited neighbor (non-parent) implies a cycle.
Key Insight: In directed graphs, cycles require a directed path that returns to a node. The recursion_stack identifies nodes on the current directed path, enabling detection of back-edges that close a cycle. In undirected graphs, cycles are simpler to detect because any previously visited node (other than the parent) forms a cycle via the undirected edge.