Sub topic 1
Representing Graphs for Traversal
Prerequisites
This chapter assumes you can write basic Python and use lists, sets, and dictionaries. You should also understand recursion and the call stack, know what vertices and edges are in directed and undirected graphs, and be able to read Big-O notation.
Representing Graphs for Traversal
An adjacency list maps each vertex to a list of the vertices its edges lead to. In Python, a dictionary of lists works well. It takes O(V + E) space, where V is the number of vertices and E is the number of edges. It also gives you a vertex's neighbors directly, and listing neighbors is the main operation a traversal performs.
For an undirected graph, list each edge in both directions.
Go Deep, Then Backtrack: The Core Idea
Depth-first search (DFS) starts at a vertex and follows one unexplored edge after another until it reaches a vertex with no new neighbors. It then backtracks to the most recent vertex that still has unexplored edges and continues from there.
Remembering Where You Have Been
Graphs can contain cycles and shared descendants. In the example, D can be reached through both B and C. Without a visited set, DFS would process D twice, and on a cyclic graph it would never stop. Checking set membership costs O(1) on average.
Writing DFS Recursively
In the recursive version, the call stack keeps track of where to backtrack to.
def dfs_recursive(graph, start):
visited = set()
order = []
def visit(node):
visited.add(node)
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visit(neighbor)
visit(start)
return order
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(dfs_recursive(graph, "A")) # ['A', 'B', 'D', 'C']Replacing Recursion with an Explicit Stack
A Python list used as a stack takes the place of the call stack, so the recursion limit no longer applies.
def dfs_iterative(graph, start):
visited = set()
order = []
stack = [start]
while stack:
node = stack.pop()
if node in visited:
continue
visited.add(node)
order.append(node)
# Push in reverse so neighbors are explored in listed order.
for neighbor in reversed(graph[node]):
if neighbor not in visited:
stack.append(neighbor)
return order
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(dfs_iterative(graph, "A")) # ['A', 'B', 'D', 'C']A vertex can be pushed onto the stack more than once, so this version marks it visited when it is popped, not when it is pushed. The continue check skips the duplicates. A common mistake is to mark vertices when they are pushed. That still visits every vertex once, but the order can differ from recursive DFS.
Exercise
If graph["A"] is changed to ["C", "B"], what order does dfs_recursive(graph, "A") return?
Show answer
['A', 'C', 'D', 'B']. DFS goes from A to C to D, backtracks to A, and then visits B. D is skipped because it has already been visited.
Exercise
Why does dfs_iterative push neighbors in reversed order?
Show answer
A stack pops the last item pushed first. Pushing the neighbors in reverse puts the first-listed neighbor on top, so it is explored first, the same way the recursive version does it.