depth-first search
- discovery time:
which is set when
is first visited during the traversal
- departure time:
which is set when
is last departured

- if
is free, we move to
and the edge
is a tree edge, and is included in the dfs tree
- if
isnt free, we dont move to
. in this case, the edge
is called a back edge in the sense that its directed from
to
and
.
isnt included in the dfs forest
process of a visit
let be a free vertex, say we're moving from the vertex
to
. before we move to
,
is marked as the vertex previous to
.
when we are at , at the beginning of the visit, we mark
as a non-free vertex. then we go through each neighbor of
one after another, skipping any neighbors that are marked as non-free.
assume that the neighbor vertex is free: we mark
as the parent of
, we timestamp the visit in
and start our visit at
. after we're done with
, we retreat to
, and renew our visit at
.
when we've gone through all of 's neighbors, we're done with our visit at
, we retreat to
.
when we finally retreat to the origin node and there's no more free vertices, the first output tree would be complete. the process is over when there's no vertices left non-visited.
the simplest way to implement this logic is using recursion, which we may see later in the function.
data structures used
the data structures used in the dfs algorithm are
- a global variable
that allows giving timestampts to each
call. the initial value of
is 1.
- for every vertex
we define 3 variables:
: the discovery time of
(value of
at the start of
)
: the departure time of
(the value of
at the end of
)
: the preceding node to
in the output tree
pseudocode
the
function initiates the data structures we need, traversal is done by
further analysis
for each
- the function
is executed once only
dfs in a directed graph
its not much different from dfs being applied to an undirected graph except that during traversal we only jump to neighbors that are descendants
if
if
topological sorting
assume that
same as dfs,