# Depth-first search

## General information

Algorithmic problem: Graph traversal

Type of algorithm: loop

## Definitions

1. For each node, an arbitrary but fixed ordering of the outgoing arcs is assumed. An arc $(v,w)$ preceding an arc $(v,w')$ in this ordering is called lexicographically smaller than $(v,w)$.
2. Let $p$ and $p'$ be two paths that start from the same node $v\in V$, but may or may not have the same end node. Let $w$ be the last common node such that the subpaths of $p$ and $p'$ from $v$ up to $w$ are identical (possibly $v=w$). If the next arc of $p$ from $w$ onwards is lexicographically smaller than the next arc of $p'$ from $w$ onwards, $p$ is said to be lexicograpically smaller than $p'$. Note that the lexicographically smallest path from $v\in V$ to $w\in V$ is well defined and unique.
3. With respect to a starting node $s\in V$, a node $v\in V$ is lexicographically smaller than $w\in V$ if the lexicographically smallest path from $s$ to $v$ is lexicographically smaller than the lexicographically smallest path from $s$ to $w$.
4. In all of the above cases, the reverse relation is called lexicographically larger.
5. A node $v\in V$ is lexicographically smaller (resp., lexicograpically larger) than a path $p$ if $v$ does not belong to $p$ and the lexicographically smallest path from the start node of $p$ to $v$ is lexicographically smaller (resp., larger) than $p$. (Note the asymmetry: In both cases, the lexicographically smallest path to $v$ is used.)
6. In all cases, we also say precedes and succeeds, respectively, instead of "is lexicograpically smaller/larger".

## Abstract view

1. Each node has two Boolean labels with semantics, "is seen" and "is finished".
2. An arborescence $A=(V',A')$ rooted at $s$ such that $V'\subseteq V$ is the set of all nodes reachable from $s$ (including $s$). For each node $v\in V'$, the path from $s$ to $v$ in $A$ is the lexicographically smallest $(s,v)$-path in $G$.

Specific characteristic: The nodes may be returned either in lexicographic order or (alternatively or simultaneously) in parenthetical order, that is: Let $v,w\in V$ such that $v$ is seen before $w$. If there is a path from $v$ to $w$, $w$ is finished prior to $v$.

Remark: Parenthetical refers to the following intuition: Whenever a node is seen, open a parenthesis, and close it once the node is finished. The result is a correct parenthetial expression: Two parentheses are either disjoint, or one is nested in the other one.

Auxiliary data:

1. A stack $S$ whose elements are nodes in $V$.
2. Each node has a current arc $a_v\in V$, which is either void or an outgoing arc $a_v=(v,w)$ of $v$. (May be viewed as an iterator over the list of all outgoing arcs.)

Invariant: Before and after each iteration:

1. $S$ forms a path $p$ from the start node $s$ to some other node, that is, the order of the nodes on $p$ is the order in which they appear in $S$ (start node $s$ at the bottom of $S$).
2. For each node not yet seen, the current arc is the first arc (or void if the node has no outgoing arcs).
3. For each node $v$ on $p$:
1. If there are arcs $(v,w)\in A$ such that $w$ is not yet seen, the current arc equals or precedes the first such arc.
2. The subpath of $p$ from the start node $s$ to $v$ is the lexicographically first $(s,v)$-path.
4. The nodes on $p$ are seen but not finished. Let $p+a$ denote the concatenation of $p$ with the current arc $a$ of the last node of $p$. The nodes that are lexicographically smaller than $p+a$ are seen and finished, and the nodes that lexicographically succeed $p+a$ are neither seen nor finished. (Note that nothing is said about the head of $a$).

Variant: Either one node is seen for the first time or finished, or (inclusive) the current arc of one node is moved forward.

Break condition: $S=\emptyset$.

## Induction basis

Abstract view: No node is finished. The start node $s$ is seen, no other node is seen. The start node is the only element of $S$. The current arc of each node is its first outgoing arc. If the nodes are to be returned in lexicographic order, the start node  is, initially, the only member of the output sequence; otherwise, the initial output sequence is empty. Arborescence $A$ is initialized so as to contain $s$ and nothing else.

Implementation: Obvious.

Proof: Obvious.

## Induction step

Abstract view:

1. Let $v$ be the last node of $p$ (=the top element of $S$).
2. While the current arc of $v$ is not void and while the head of the current arc is labeled as seen: Move the current arc one step forward.
3. If the current arc of $v$ is not void, say, $a_v=(v,w)$:
1. Insert $w$ and $(v,w)$ in $A$.
2. Push $w$ on $S$.
3. Label $w$ as seen.
4. If the output order is the lexicographical one: Append $w$ to the output sequence.
4. Otherwise:
1. Remove $v$ from $S$
2. Label $v$ as finished.
3. If the output order is the parenthetical one: Put $v$ in the output sequence.

Implementation: Obvious.

Proof: The loop variant is obviously fulfilled.

The first point of the invariant is obviously fulfilled, too. The second point follows from the fact that the current arc of a node is initialized to be the node's very first outgoing arc and only changed after the node is labeled as seen. Point 3.1 follows from the fact that, in step 2, the current arc never skips an arc that points to an unseen node.

For point 3.2, let $p'$ be the lexicographically smallest $(s,v)$-path. Moreover, let $w\neq v$ be the last node on $p$ and $p'$ such that both paths are identical from $s$ to $w$ (possibly, $w=s$). Further, let $u$ and $u'$ be the immediate successors of $w$ on $p$ and $p'$, respectively. Then $u'$ has been seen before $u$ because $(w,u)$ is the arc over which $u$ was seen for the first time, and $(w,u')$ precedes $(w,u)$. Note that $v$ has not been seen earlier than $u$ (in fact, later than $u$, unless $v=u$). In summary, $u'$ has been seen before $v$. Since there is a path from $u'$ to $v$, the correctness proof below will prove that $v$ was finished before $u'$. This contradicts the induction hypothesis (point 4 of the invariant).

When a node is pushed on $S$, it is neither seen nor finished immediately before that iteration and then labeled as seen in that iteration. The node is finished when it leaves $S$. Both facts together give the first sentence of point 4. The other statements of point 4 follow from the observation that the concatenation of $p$ with the current arc of the endnode of $p$ increases lexicographically in each iteration in which Step 3 applies.

## Correctness

It is easy to see that each operation of the algorithm is well defined. Due to the variant, the loop terminates after a finite number of steps. Immediately before the last iteration, $p$ consists of the start node $s$ only, and the current arc of $s$ is void. Therefore, all nodes reachable from $s$ except for $s$ itself are lexicographically smaller than $p$ at that moment. Due to point 4 of the invariant, all of these nodes are finished. In the last iteration, $s$ is finished as well.

So, it remains to show that the specific characteristic is fulfilled in both cases. Due to point 3.2 of the invariant, a node is seen for the first time via its lexicographically smallest path from $s$. Since the current path increases lexicographically in each iteration, the nodes are labeled as seen in lexicographic order. In summary, the lexicographical order is correct.

So consider the second, the parenthetical case. Let $v$ be seen before $w$ and assume there is a path from $v$ to $w$. We have to show that $w$ is finished prior to $v$. Let $p'$ denote the lexicographically smallest $(v,w)$-path. There is a stage in which this path is a subpath of the current path $p$. Clearly, $v$ cannot be removed from $S$ before $w$. This proves the claim.

## Complexity

Statement: The asymptotic complexity is in $\Theta(|V|+|A|)$ in the worst case.

Proof: For every node reachable from $s$ (including $s$), the algorithm processes each of its outgoing arcs exactly once. And from each of these nodes, the algorithm goes backwards exactly once. Obviously, each of these steps requires a constant number of operations.

## Remark

Alternatively, DFS could be implemented as a recursive procedure. However, this excludes the option to implement DFS as an iterator, which means to turn the loop inside-out (cf. remarks on graph traversal).

## Pseudocode recursive implementation

#### DFS(G)

for each vertex uV [G]
do color[u] ← WHITE
π[u] ← NIL
time ← 0
do if color[u] == WHITE
then DFS-VISiT(u)

#### DFS-VISIT(u)

color[u] ← GRAY
timetime + 1
d[u] ← time
do if color[v] = WHITE
then π [v] ← u
DFS-VISIT(v)
color[u] ← BLACK
f[u] ← timetime + 1

## Pseudocode stack implementation

#### DFS(s)

S = new Stack()
s.IsSeen = true
S.push(s)
while S ≠ ∅
n = S.peek()
a = (v, w) = n.nextArc()
if a == null
n.IsFinised = true
S.pop()
else if w.IsSeen == false
w.IsSeen = true
S.push(w)