Lecture 12
Graph-Based Algorithms
CSE373: Design and Analysis of Algorithms
Properties of DFS
Parentheses structure: If we represent the
discovery of vertex with a left parenthesis
and represent its finishing by a right
parenthesis , then the history of discoveries
and finishings makes a well-formed expression
in the sense that the parentheses are properly
nested.
Properties of DFS
This
yields the parentheses theorem: For any
two vertices and , exactly one of the following
three conditions holds:
1. the intervals and are entirely disjoint, and
neither nor is a descendant of the other in the
depth-first forest
2. the interval is contained entirely within the
interval , and is a descendant of in a depth-first
tree, or
3. the interval is contained entirely within the
interval , and is a descendant of in a depth-first
tree.
Properties of DFS
Classifying Edges
Consider edge in directed graph
w.r.t. DFS forest
1. tree edge: is a child of
2. back edge: is an ancestor of
3. forward edge: is a descendant of (but not
a child)
4. cross edge: all other edges. They can go
between vertices in the same depth-first
tree, as long as one vertex is not an ancestor
of the other, or they can go between vertices
in different depth-first trees.
Classifying Edges
The
DFS algorithm can be used to classify graph
edges by assigning colors to them. Each edge
can be classified by the color of the vertex that
is reached when the edge is explored:
white indicates a tree edge
gray indicates a back edge
black indicates a forward or cross edge. An
edge is
a forward edge if and
a cross edge if
Classifying Edges
DFS Application: Topological Sort
Given
a directed acyclic graph (DAG), find a
linear ordering of the vertices such that if is an
edge, then precedes in the ordering.
DAG indicates precedence among events:
events are graph vertices, edge from to means
event has precedence over event
Partial order because not all events have to be
done in a certain order
DFS Application: Topological Sort
Precedence Example:
Consider how Professor Bumstead gets dressed
for his office.
undershorts, pants, shirt, jacket, tie, watch, belt,
shoes, socks
Certain garments must before others (e.g.,
socks before shoes)
For other events, it doesn't matter (e.g., socks
and pants)
DFS Application: Topological Sort
directed edge in the DAG indicates that
A
garment must be donned before garment . A
topological sort of this DAG therefore gives an
order for getting dressed.
DFS Application: Topological Sort
The
following simple algorithm topologically sorts a
DAG:
TOPOLOGICAL-SORT(G)
1 call DFS(G) to compute finishing times for each vertex
2 as each vertex is finished, insert it onto the front of a linked list
3 return the linked list of vertices
We can perform a topological sort in time, since
depth-first search takes time and it takes time to
insert each of the vertices onto the front of the
linked list.
DFS Application: Topological Sort