Sub topic 7
Visiting Every Vertex: The DFS Forest
This chapter assumes you already know recursive DFS from a single start vertex, the iterative stack-based version, and why a shared visited set stops revisits. The code uses Python dictionaries as adjacency lists, with each vertex mapped to a list of its neighbors.
Why One Start Vertex Is Not Enough
A DFS launched from one vertex reaches only the vertices reachable from it. In an undirected graph that is a single connected piece. In a directed graph it can be even less, because edges only go one way. Take a graph where A → B → C, D → B, D → E, and F has no edges at all. Starting at A visits A, B, and C. It never sees D, E, or F.
Many algorithms need every vertex: topological sort, cycle detection over a whole graph, counting components. The fix is an outer loop. Go through every vertex, and if it has not been visited yet, start a new DFS from it. All launches share one visited set, so each vertex is explored exactly once in total.
The DFS Forest
Each launch from the outer loop builds a DFS tree. Its root is the vertex the launch started from. Its edges are the tree edges, meaning the edges DFS followed to reach a vertex for the first time. The collection of all these trees is the DFS forest.
The forest is usually stored as a parent map. Each vertex maps to the vertex it was discovered from, and roots map to None. With a parent map you can rebuild any tree, find the root a vertex belongs to, and trace a path back to it.
def dfs_forest(graph, roots=None):
"""Return (trees, parent) for a DFS over every vertex.
trees -- list of lists; each inner list is one tree in discovery order
parent -- dict mapping each vertex to its DFS parent (None for roots)
roots -- optional order in which the outer loop tries start vertices
"""
visited = set()
parent = {}
trees = []
def visit(node, tree):
visited.add(node)
tree.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
parent[neighbor] = node
visit(neighbor, tree)
for root in (roots if roots is not None else graph):
if root not in visited:
parent[root] = None
tree = []
visit(root, tree)
trees.append(tree)
return trees, parent
graph = {
"A": ["B"],
"B": ["C"],
"C": [],
"D": ["B", "E"],
"E": [],
"F": [],
}
trees, parent = dfs_forest(graph)
print(trees) # [['A', 'B', 'C'], ['D', 'E'], ['F']]
print(parent) # {'A': None, 'B': 'A', 'C': 'B', 'D': None, 'E': 'D', 'F': None}The outer loop launches three times, so the forest has three trees. F is a tree with one vertex. Isolated vertices always become their own trees, which is easy to forget when you count trees by hand.
The dashed edge D → B is part of the graph but not part of the forest. When the second launch explored D, vertex B was already visited, so DFS skipped it.
Recovering Paths from the Parent Map
The parent pointers in each tree lead back to the root. Following them gives the path DFS took to reach a vertex:
def path_from_root(parent, node):
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1]
print(path_from_root(parent, "C")) # ['A', 'B', 'C']
print(path_from_root(parent, "E")) # ['D', 'E']This path is a valid path in the graph. It is usually not the shortest one, since DFS goes deep instead of wide. If you need shortest paths in an unweighted graph, use BFS. A later chapter compares the two.
The Forest Depends on Order
There are many possible DFS forests for one graph. The forest you get depends on the order in which the outer loop tries roots and the order of each adjacency list. Here is the same graph with D tried first:
trees, parent = dfs_forest(graph, roots=["D", "A", "B", "C", "E", "F"])
print(trees) # [['D', 'B', 'C', 'E'], ['A'], ['F']]B and C now belong to D's tree, and A sits alone because its only neighbor was already taken. In directed graphs even the number of trees can change. For the two-vertex graph X → Y, starting at X gives one tree, and starting at Y gives two.
Undirected graphs behave differently. Every launch floods its whole connected component, and no edge can join two trees. So the number of trees always equals the number of connected components, whatever the order. The Connected Components chapter builds on this.
Iterative Version
Recursive DFS can go about as deep as the longest path it follows. Python's default recursion limit is roughly 1000 frames, so a long chain graph raises RecursionError. The iterative version builds the same forest using a stack. Each stack entry carries the candidate parent, and the parent is recorded only when the vertex is popped and marked visited.
def dfs_forest_iterative(graph):
visited = set()
parent = {}
trees = []
for root in graph:
if root in visited:
continue
tree = []
stack = [(root, None)]
while stack:
node, par = stack.pop()
if node in visited:
continue
visited.add(node)
parent[node] = par
tree.append(node)
for neighbor in reversed(graph[node]):
if neighbor not in visited:
stack.append((neighbor, node))
trees.append(tree)
return trees, parent
chain = {i: [i + 1] for i in range(100_000)}
chain[100_000] = []
trees, _ = dfs_forest_iterative(chain)
print(len(trees), len(trees[0])) # 1 100001A vertex can be pushed more than once by different neighbors. The most recent push is popped first, which matches the parent the recursive version would assign. Stale entries are skipped by the if node in visited check.
Making Sure Every Vertex Is a Key
The outer loop can only start from vertices that are keys of the dictionary. If you build a graph from an edge list and add only source vertices as keys, sinks are missing. Then graph[node] raises KeyError, and isolated vertices are never seen. Normalize the graph first:
def build_graph(edges, vertices=()):
graph = {v: [] for v in vertices}
for u, v in edges:
graph.setdefault(u, []).append(v)
graph.setdefault(v, [])
return graph
g = build_graph([("A", "B"), ("D", "B")], vertices=["F"])
print(g) # {'F': [], 'A': ['B'], 'B': [], 'D': ['B']}Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Creating a new `visited` set for each launch | Vertices appear in several trees, and running time grows toward O(V·(V+E)) | Share one `visited` set across the outer loop |
| Sink vertices missing as dictionary keys | `KeyError` inside `visit` | Add every vertex as a key, even with an empty list |
| Isolated vertices left out of the input | Tree count too low | Pass the full vertex set, not just the edges |
| Counting trees in a directed graph as "components" | Count changes with root order | Use strongly connected components for directed graphs |
| Deep recursion on long paths | `RecursionError` | Use the iterative version |
The outer loop does not change the cost. Each vertex is visited once and each adjacency list is scanned once, so the full traversal still runs in O(V + E). The loop adds only O(V) membership checks.
Exercise
An undirected graph has vertices 1 through 7 and edges 1–2, 2–3, 4–5, and 6–6 (a self-loop). How many trees does the DFS forest have, and does the answer depend on the order of the outer loop?
Show answer
Four trees: {1, 2, 3}, {4, 5}, {6}, and {7}. The self-loop does not connect 6 to anything else, and 7 is isolated. In an undirected graph the tree count always equals the number of connected components, so it does not depend on order.
Exercise
For the directed graph P → Q, Q → R, S → R, which order of roots gives the most DFS trees, and how many trees does it give?
Show answer
Trying R first, then Q, then P, then S gives four trees, one per vertex. R has no outgoing edges. When Q is tried, R is already visited, and the same thing happens for P with Q and for S with R. Any order that tries P before Q and R gives fewer trees.
Exercise
Using the parent map from dfs_forest(graph) on the chapter's example graph, write an expression that returns the root of the tree containing a given vertex v.
Show answer
Follow parents until reaching None: r = v then while parent[r] is not None: r = parent[r]. For v = "C" this gives "A", and for v = "E" it gives "D".