Data Structures · Visualization
Graph: Cycle Detection (DFS)
Graph
A cycle exists in a graph if you can start at a node, follow edges, and return to that same node without repeating an edge. Time: O(V + E). Space: O(V) for tracking state and the recursion stack.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: Cycle Detection (DFS)
GraphA cycle exists in a graph if you can start at a node, follow edges, and return to that same node without repeating an edge. DFS detects cycles by tracking not just 'visited' nodes but also nodes currently 'in progress' along the current path; if DFS ever reaches a neighbor that is still in progress on the current path, a cycle has been found. (For undirected graphs, a simpler check is: encountering a visited neighbor that isn't the immediate parent.)
How Cycle Detection (DFS) Works
- Start DFS from a node, marking it as 'in progress' (on the current path).
- For each neighbor, if it's already 'in progress', a cycle is found.
- If the neighbor is unvisited, recursively DFS into it.
- Once all of a node's neighbors are explored, mark it as fully 'done' (no longer in progress).
Cycle Detection (DFS) Worked Example
Input: Directed graph with edges A->B, B->C, C->A
- DFS from A: mark A in-progress, go to B
- Mark B in-progress, go to C
- Mark C in-progress, go to A
- A is already 'in progress' → cycle detected!
Output: true (a cycle exists: A -> B -> C -> A)
Press ▶ Run to watch it step by step.
def has_cycle(graph):
state = {} # 0 = visiting, 1 = done
def dfs(v):
state[v] = 0
for nxt in graph.get(v, []):
if nxt in state:
if state[nxt] == 0:
return True # back edge
elif dfs(nxt):
return True
state[v] = 1
return False
for v in graph:
if v not in state and dfs(v):
return True
return False
# example: detect cycleBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Cycle Detection (DFS) Time & Space Complexity
When to Use Cycle Detection (DFS)
- Detecting circular dependencies in build systems or package managers
- Deadlock detection in operating systems (resource allocation graphs)
- Validating that a workflow or task graph has no circular requirements
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.