Spot the route back into the route.
Distinguish visited vertices from vertices still active on the current DFS path.
01 Model the idea
In a directed graph, an edge into the active DFS path proves a cycle. An edge to a previously completed vertex does not necessarily do so. Three states—unseen, active, complete—capture that distinction. Explore every component, not just one start vertex, when the question asks whether the entire graph contains a cycle.
Active vertices are exactly the unfinished DFS path.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
MARK a vertex active on entry
REJECT an edge to an active vertex
MARK the vertex complete on exit03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def has_cycle(graph):
state = {node: 0 for node in graph}
def visit(node):
state[node] = 1
for neighbour in graph[node]:
if state[neighbour] == 1: return True
if state[neighbour] == 0 and visit(neighbour): return True
state[node] = 2
return False
return any(state[node] == 0 and visit(node) for node in graph)
print(has_cycle({"A": ["B"], "B": ["C"], "C": ["A"]}))
print(has_cycle({"A": ["B", "C"], "B": ["C"], "C": []}))True False
- 1
An active vertex has been entered but not completed. A back edge into that path closes a directed loop.
- 2
The second fixture has multiple routes to C but no directed cycle. Treating every edge to a visited vertex as a cycle would be wrong.
- 3
This recursive implementation can exceed Python’s depth limit on a long path. Use an explicit stack with entry/exit state for deep production graphs. Every referenced neighbour must appear in the vertex map.
04 Count the cost
O(V + E)
O(V) state and recursion stack
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Use a topological-processing baseline to recognise a directed cycle.
Reveal one possible solution +
from collections import deque
def has_cycle(graph):
degree = {node: 0 for node in graph}
for neighbours in graph.values():
for node in neighbours: degree[node] += 1
queue = deque(node for node in graph if degree[node] == 0)
removed = 0
while queue:
node = queue.popleft(); removed += 1
for neighbour in graph[node]:
degree[neighbour] -= 1
if degree[neighbour] == 0: queue.append(neighbour)
return removed != len(graph)
print(has_cycle({"A": ["B"], "B": ["A"]}))06 Check your reasoning
Which directed DFS edge proves a cycle?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.