Sub topic 7
Visiting Every Vertex: The DFS Forest
This chapter assumes you already know recursive DFS from a single start vertex, the visited-set technique, and the difference between directed and undirected graphs.
Why One Start Vertex Is Not Enough
A DFS launched from one vertex reaches only the vertices reachable from it. In a directed graph, or in an undirected graph with separate pieces, some vertices may never be touched. Many algorithms need every vertex processed. Cycle detection, topological sort and component counting are examples.
The fix is an outer loop. Walk over every vertex. Whenever you find one that has not been visited yet, start a fresh DFS from it. All the launches share a single visited set, so no vertex is explored twice.
Trees, Roots, and the Forest
Each time DFS moves from a vertex u to an unvisited neighbor v, the edge u → v becomes a tree edge, and u becomes the parent of v. One launch from the outer loop builds one tree. Its root is the vertex the loop started from. Together, the trees make up the DFS forest.
The forest is a by-product of the traversal. It records which vertex discovered which. Later chapters build on that record when they classify edges and compute finish times.
Building the Forest in Code
The version below stores a parent map. A root has parent None. The map also works as the visited set, because a vertex is in it if and only if it has been discovered.
def dfs_forest(graph):
parent = {}
roots = []
def visit(node):
for neighbor in graph[node]:
if neighbor not in parent:
parent[neighbor] = node # tree edge node -> neighbor
visit(neighbor)
for node in graph:
if node not in parent:
parent[node] = None # node becomes a root
roots.append(node)
visit(node)
return roots, parent
graph = {"A": ["B"], "B": ["C"], "C": [], "D": ["B", "E"], "E": [], "F": []}
roots, parent = dfs_forest(graph)
print(roots) # ['A', 'D', 'F']
print(parent) # {'A': None, 'B': 'A', 'C': 'B', 'D': None, 'E': 'D', 'F': None}The first launch from A discovers B and C. When the loop reaches D, the vertex B is already visited, so the edge D → B is not a tree edge. Only E joins D's tree. F has no edges, so it forms a tree of one vertex.
Common Mistakes
| Mistake | Consequence |
|---|---|
| Resetting `visited` inside the outer loop | Vertices are re-explored, and the run takes O(V·E) time instead of O(V + E) |
| Forgetting vertices that have no outgoing edges | `graph[node]` raises `KeyError` when such a vertex appears only as a neighbor |
| Assuming the forest is unique | The roots and tree shapes depend on loop order and neighbor order |
Cost
The outer loop adds O(V) work. Each vertex is still discovered once, and each adjacency list is still scanned once, so the whole forest is built in O(V + E) time.
Exercise
Run dfs_forest on the example graph, but loop over the vertices in the order F, E, D, C, B, A, keeping each neighbor list unchanged. Which vertices become roots, and how many trees are there?
Show answer
The roots are F, E, D and A, so there are four trees. F and E have no outgoing edges, so each is a tree of one vertex. D discovers B, and B discovers C. E is already visited at that point. When the loop reaches C and B they are already visited. A finds B visited, so A is a tree of one vertex.