Chapter 24: Graphs and DFS
Motivation
Graphs are among the most general and important data structures. They are used to
represent a set of
objects
and a
relation
among the objects. In engineering problems, they
are used to represent electrical circuits, chemical molecules, highway maps,
manufacturing processes, and structural and geometric models. In this chapter we will
introduce graphs, give a few of their properties, and define an important algorithm on
graphs called depth-first search or DFS.
Graphs
A graph consists of
nodes
(or
vertices
) and
edges
. Each node holds some data, and an
edge joins two nodes. In the example below, the nodes are A, B, C, D.
The edges are written as the set of nodes that they join. So the edge from A to C is
written {A, C}. The list of all the edges is the graph is [{A, B} {A, C} {B, C} {C, D}].
The graph above is an
undirected
graph. That means that we can write {A, B} or {B, A}
and we mean the same edge. In a
directed
graph, we would write (A, B) for an edge from
A to B, and (B, A) for an edge from B to A. These would be different edges. We indicate
the direction with an arrowhead. So in a directed graph, an edge from A to B would be
written:
Paths in Graphs