Depth-First Search
Overview
Depth-first search operates on a graph

To keep track of progress, DFS colors each vertex white, gray, or black. All vertices start out white. They are colored gray upon discovery. They are painted black once all edges have been explored.
Vertices also typically have two timestamps recorded: on discovery and on finish.
Depth-First Forests
To color an entire graph black, BFS may need to be invoked multiple times. After each invocation of BFS, a new invocation can be run with any remaining white vertex as the source. Each invocation yields a depth-first tree. Multiple invocations yield a depth-first forest.
Edge Classification
A depth-first forest can contain four different types of edges:
- A tree edge is an edge
such that was first discovered by exploring edge . - A back edge is an edge
connecting vertex to an ancestor . - Self-loops are considered back edges.
- A forward edge is a non-tree edge
connecting vertex to a proper descendant . - A cross edge is any other edge.
Parenthesis Theorem
In any depth-first search of a graph, for any two vertices
- The intervals
and are disjoint. - No ancestor-descendant relation exists between
and .
- No ancestor-descendant relation exists between
- The interval
is contained entirely within . is a descendant of .
- The interval
is contained entirely within . is a descendant of .
White-Path Theorem
In a depth-first forest of a directed or undirected graph
Topological Sort
A topological sort of a directed acyclic graph
Call depth-first search on
to compute finish times for each vertex . As each vertex is finished, insert it onto the front of a linked list. Return the list when all vertices are processed.
Kosaraju's Algorithm
Let
- Call
to compute finish times for each vertex . - Create
. - Call
, but in the main loop of DFS, consider the vertices in order of decreasing . - Output the vertices of each tree in the forest formed in line (3) as a separate strongly connected component.