
Traversing a graph: BFS and DFS
(CLRS 22.2, 22.3)
The most fundamental graph problem is traversing the graph.
•There are two standard (and simple) ways of traversing all vertices/edges in a graph in a
systematic way: BFS and DFS.
•Most fundamental algorithms on graphs (e.g finding cycles, connected components) are ap-
plications of graph traversal.
•Like finding the way out of a maze (maze = graph). Need to be careful to not get stuck in
the graph, so we need to mark vertices that we’ve encountered; and we need to make sure we
don’t skip anything.
•Basic idea: over the course of the traversal a vertex progresses from undiscovered, to discov-
ered, to completely-discovered:
–undiscovered: initially (WHITE)
–discovered: after it’s encountered, but before it’s completely explored (GRAY)
–completely explored: the vertex after we visited all its incident edges (BLACK)
•We start with a single vertex and evaluate its outgoing edges:
–If an edge goes to an undiscoverd vertex, we mark it as discovered and add it to the list
of discovered vertices.
–If an edge goes to a completely explored vertex, we ignore it (we’ve already been there)
–If an edge goes to an already discovered vertex, we ignore it (it’s on the list).
•Analysis: Each edge is visited once (for directed graphs), or twice (undirected graphs — once
when exploring each endpoint) ⇒O(|V|+|E|)
•Depending on how we store the list of discovered vertices we get BFS or DFS:
–queue: explore oldest vertex first. The exploration propagates in layers form the starting
vertex.
–stack: explore newest vertex first. The exploration goes along a path, and backs up only
when new unexplored vertices are not available.
1