Take one path further.
Explore a graph with a stack and avoid cycling indefinitely.
01 The idea
Depth-first search explores down one branch before returning to other candidates. An explicit stack avoids Python recursion depth for a long path. A visited set prevents infinite revisits in a cyclic graph. DFS is useful for reachability, connected components, and as a component of other algorithms, but it does not generally return a shortest unweighted path.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def dfs(graph, start):
stack, seen, order = [start], set(), []
while stack:
node = stack.pop()
if node in seen: continue
seen.add(node); order.append(node)
stack.extend(reversed(graph.get(node, [])))
return order
graph = {"A": ["B", "C"], "B": ["D"], "C": [], "D": ["A"]}
print(dfs(graph, "A"))['A', 'B', 'D', 'C']
03 Under the hood
- 1
The stack processes the newest candidate first. Reversing neighbour insertion preserves the fixture’s left-to-right visit preference.
- 2
A node may enter the stack more than once, but the seen check ensures its adjacency list is processed only once.
- 3
For adjacency lists, traversal is O(V + E) over the reachable region. In a directed graph, reachability from one start does not imply reverse reachability or membership in one strongly connected component.
04 Your turn, builder
Use DFS to count how many vertices are reachable from A in a graph with an unreachable Z.
Reveal one possible solution +
graph = {"A": ["B"], "B": [], "Z": []}
stack, seen = ["A"], set()
while stack:
node = stack.pop()
if node not in seen:
seen.add(node); stack.extend(graph[node])
print(len(seen))05 Check your signal
Does DFS generally guarantee the shortest unweighted route?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.