Note. — If each vertex in a graph is to be traversed by a tree-based algorithm (such as DFS or BFS), then the algorithm must be called at least once for each
connected component of the graph. This is easily accomplished by iterating through all the vertices of the graph, performing the algorithm on each vertex that is still unvisited when examined.
Depth-first search A depth-first search (DFS) is an algorithm for traversing a finite graph. DFS visits the child vertices before visiting the sibling vertices; that is, it traverses the depth of any particular path before exploring its breadth. A stack (often the program's
call stack via
recursion) is generally used when implementing the algorithm. The algorithm begins with a chosen "root" vertex; it then iteratively transitions from the current vertex to an adjacent, unvisited vertex, until it can no longer find an unexplored vertex to transition to from its current location. The algorithm then
backtracks along previously visited vertices, until it finds a vertex connected to yet more uncharted territory. It will then proceed down the new path as it had before, backtracking as it encounters dead-ends, and ending only when the algorithm has backtracked past the original "root" vertex from the very first step. DFS is the basis for many graph-related algorithms, including
topological sorts and
planarity testing.
Pseudocode •
Input: A graph
G and a vertex
v of
G. •
Output: A labeling of the edges in the connected component of
v as discovery edges and back edges.
procedure DFS(
G,
v)
is label
v as explored
for all edges
e in
G.incidentEdges(
v)
do if edge
e is unexplored
then w ←
G.adjacentVertex(
v,
e)
if vertex
w is unexplored
then label
e as a discovered edge recursively call DFS(
G,
w)
else label
e as a back edge
Breadth-first search A breadth-first search (BFS) is another technique for traversing a finite graph. BFS visits the sibling vertices before visiting the child vertices, and a
queue is used in the search process. This algorithm is often used to find the shortest path from one vertex to another.
Pseudocode •
Input: A graph
G and a vertex
v of
G. •
Output: The closest vertex to
v satisfying some conditions, or null if no such vertex exists.
procedure BFS(
G,
v)
is create a queue
Q enqueue
v onto
Q mark
v while Q is not empty
do w ←
Q.dequeue()
if w is what we are looking for
then return
w for all edges
e in
G.adjacentEdges(
w)
do x ←
G.adjacentVertex(
w,
e)
if x is not marked
then mark
x enqueue
x onto
Q return null ==Applications==