The University of Texas at Austin
Department of Computer Sciences
Professor Vijaya Ramachandran
Depthfrst Search
CS357: ALGORITHMS, Spring 2006
1
Depthfrst Search
Let
G
= (
V, E
) be a directed or undirected graph. Given a vertex
a
∈
V
, depthFrst search
identiFes all vertices
v
such that either
v
=
a
or there is a path from
a
to
v
in
G
. It does so
by setting
mark
(
v
) =
T
for all such vertices, where initially,
mark
(
v
) =
F
for all vertices.
(Note that
mark
=
F
and
mark
=
T
correspond to colors white and gray, respectively, in
the pseudocode in the textbook. The color black is not really needed in the code, it is used
only to facilitate understanding the algorithm.)
Dfs
(
v
)
1.
mark
(
v
) :=
T
2.
For
each vertex
w
∈
Adj
[
v
]
do
3.
iF
mark
(
w
) =
F
then
4.
π
(
w
) :=
v
5.
Dfs
(
w
)
f
roF
(
color
(
v
) :=
black
)
end
{
procedure
Dfs
}
Main Program
For
each
u
∈
V
do
mark
(
u
) :=
F
π
(
u
) :=
NIL
roF
Dfs
(
a
)
end
{
Main Program
}
Bound on Running Time
Let

V

=
n
and

E

=
m
. ±or an analysis of the running time of this algorithm, we note the
following:
0. The initialization in the Main Program takes time
O
(
n
).
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document1. For each vertex
v
∈
V
,
dfs
(
v
) is called at most once. The reason for this is that
(i) a call to
dfs
(
v
) is made only only if
mark
(
v
) =
F
,
(ii)
mark
(
v
) is set to
T
upon execution of
dfs
(
v
), and
(iii)
mark
(
v
) is never reset to
F
.
2. The time taken by the call
dfs
(
v
),
outside of the time taken by recursive calls within
dfs
(
v
) is 1 +
O
(
deg
+
(
v
)) (the outdegree of
v
), since the only computation outside of the
recursive calls is to set
mark
(
v
) to
T
and to check if
mark
(
w
) =
F
for each edge (
v, w
) that
is outgoing from
v
.
By 0, 1, and 2, the running time of this algorithm is
O
(
n
) +
s
v
∈
V
(1 +
O
(
deg
+
(
v
)) =
O
(
n
) +
n
+
O
(
m
) =
O
(
m
+
n
)
In deriving the above expression, we used the fact that the sum of the outdegrees of the
vertices in
G
is
m
.
The above analysis also shows that the algorithm terminates.
Correctness.
In the following, we will say that a vertex
v
is
unmarked
if
mark
(
v
) =
F
, and it is
marked
if
mark
(
v
) =
T
. Note that unmarked vertices are ‘white’ vertices and marked vertices are
vertices that are either ‘gray’ or ‘black’ according to the pseudocode in the textbook.
Theorem 1.1
Consider a call to
Dfs
(
u
)
invoked during the execution of the main program.
We claim that this call to
Dfs
(
u
)
makes a recursive call to
Dfs
(
v
)
iF there is a path of
unmarked vertices from
u
to
v
at the time when
Dfs
(
u
)
is called.
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '06
 Ramachandran
 Algorithms, Graph Theory, Glossary of graph theory, Directed acyclic graph

Click to edit the document details