Properties of DFS
Dependencies:
It returns a DFS forest of
The algorithm
DFS maintains 5 attributes for every vertex:
- Start time:
- Finish time:
Initially, for every vertex
Let
DFS algorithm on
for u in G.V:
color[u] = white
π[u] = null
time = 0
def visit(u, d):
assert(color[u] == white)
depth[u] = d
color[u] = gray
time += 1
s[u] = time
for v in adj[u]:
if color[v] == white:
π[v] = u
visit(v, d+1)
color[u] = black
time += 1
f[u] = time
for u in G.V:
if color[u] == white:
visit(u, 0)
As visit(u)
iterates over adj[u]
, we say that the edge
Vertices with depth 0 are called root vertices.
When DFS terminates, root vertices are the only vertices to have visit(v)
calls.
When DFS terminates,
Properties of DFS
-
visit
is called on each vertex exactly once, becausevisit
is only called on white vertices andvisit(u)
makes gray before any recursive calls. -
During the execution of DFS, whenever
time
is set, the following invariant holds on :- If
visit(u)
hasn't yet been called, is white. - If
visit(u)
was called butvisit(u)
hasn't ended, is gray. - If
visit(u)
has ended, is black.
- If
-
is acyclic because for every edge in , . Since is an acyclic predecessor graph, it is a union of rooted trees. Therefore, is also called the DFS forest of . -
visit(v)
was called duringvisit(u)
iff is a descendant of in . Proof: -
DFS takes
time to run, because it visits each vertex exactly once and reads its adjacency list during the visit. -
During DFS, the function call stack can have at most
visit
calls. DFS also stores attributes for each vertex. Therefore, its auxiliary memory requirement is .
Dependency for:
Info:
- Depth: 3
- Number of transitive dependencies: 8
Transitive dependencies:
- /sets-and-relations/equivalence-classes
- /sets-and-relations/relation-composition-is-associative
- /sets-and-relations/equivalence-relation
- Graph
- Transpose of a graph
- Path in Graph
- Rooted tree
- Forest