DFS
DFS
1
Background
DFS will process the vertices first deep and then wide.
After processing a vertex it recursively processes all
of its descendants
2
DFS
Graph is . The algorithm works in discrete
time steps. Each vertex is given a “discovery” time
when it is first processed and a “finish” time,
when all of its descendants are finished.
Example:
11/14
d e d e 12/13
root
2/5
b a b 1/10
6/9
f a f
root
7/8
g g
c c 3/4
original graph
Two source vertices a, d
3
What Does DFS Do
Given a digraph , it traverses all vertices
of and
4
The DFS Forest
DFS Forest: DFS creates a forest , a
collection of rooted trees, where
where DFS calls are made
11/14
d e d e 12/13
root
2/5
b a b 1/10
6/9
f a f
root
7/8
g g
c c 3/4
original graph
Two source vertices a, d
5
Idea of the DFS Algorithm
explored.
was discovered.
6
Idea of the DFS Algorithm by Example
11/14
d e d e 12/13
root
2/5
b a b 1/10
6/9
f a f
root
7/8
g g
c c 3/4
original graph
Two source vertices a, d
7
Four Arrays for the DFS Algorithm
, the color of each vertex visited: white
means undiscovered, gray means discovered but
not finished processing, and black means finished
processing.
, the predecessor pointer, pointing back to
the vertex that discovered .
, the discovery time, a counter indicating when
vertex is discovered.
, the finishing time, a counter indicating when
the processing of vertex (and all its descen-
dants ) is finished.
8
Depth-First Search (DFS) Algorithm
time=0;
for each u in V
if(color[u]==W) DFSVisit(u); // Start new tree
9
Running Time Analysis of DFS
DFS(G)
for each u in V
color[u]=W; pred[u]=NIL;
time=0;
for each u in V
if(color[u]==W) DFSVisit(u); (tests)
Sum:
DFSVisit(u) (call)
color[u]=G;
d[u]=++time;
for each v in adj[u]
if(color[v]==W) outdeg(u) (tests)
pred[v]=u; DFSVisit(v); outdeg(u)
color[u]=B;
f[u]=++time;
Sum: outdeg outdeg
10
Running Time Analysis of DFS – Continued
We have
outdeg
and
outdeg
Hence
Therefore .
11
Questions about DFS
12
On-line Example of DFS
a b
c d
e f
13