Short answer: Depth-first search follows an edge as far as it can, then backtracks, using a stack or the call stack. Each vertex receives a discovery time and a finish time. Those times classify every edge as tree, back, forward, or cross, and the finish order is the input to topological sort and to Kosaraju’s strongly connected components. The scan is Θ(V+E). It does not compute shortest paths.
What the problem actually asks
Some graph facts are about ancestry in a search forest, not about distance. A back edge points at an ancestor and, in a directed graph, closes a cycle. A finish time records the moment the entire descendant subtree is done. Algorithms that need those facts want a traversal that stays with one child until that child is exhausted.
The stack produces that stay. A queue would finish a level before any grandchild, and the finish times would mean something else. The price is that the path by which a vertex was discovered can be arbitrarily longer than a shortest path.
What the algorithm guarantees
One adjacency-list search runs in Θ(V+E) and uses Θ(V) stack space in the worst case, a single path through every vertex. Discovery and finish times are integers from 1 to 2V. The parenthesis theorem says the interval [discovery, finish] of a vertex either contains the interval of another vertex or is disjoint from it. Containment means ancestry in the depth-first forest.
In a directed graph an edge u→v is a tree edge if it discovers v, a back edge if v is an ancestor of u, a forward edge if v is a descendant and the edge is not the tree edge, and a cross edge otherwise. In an undirected graph every non-tree edge is a back edge to an ancestor. A back edge in a directed graph witnesses a cycle. An undirected cycle is a back edge to an ancestor that is not the parent.
The working steps
- Mark every vertex undiscovered. The clock starts at zero.
- For each vertex that is still undiscovered, begin a search there. This outer loop is what finds every component or every source-side piece of a directed graph.
- On entering u, mark it discovered, stamp the discovery time, and scan its adjacency list.
- Recur, or push, on each undiscovered neighbor. After the list is exhausted, stamp the finish time.
- Classify edges from the colors at the moment they are examined: undiscovered means tree, discovered-and-unfinished means back, finished means forward or cross depending on the timestamps.
The timestamps are a traversal record. They are not distances. Using the tree path as a route is safe only when any path will do. Shortest unweighted paths belong to breadth-first search. The same timestamps, read in reverse finish order, are a topological order when the directed graph has no back edge.
Approaches that look simpler and fail
| Approach | Why it fails when a depth-first tree is read as a shortest-path tree |
|---|---|
| Report the tree path as a minimum-hop path | The search may dive down a long branch before a one-edge path is ever looked at. Hop count belongs to a queue. |
| Ignore the outer loop over undiscovered vertices | A directed graph, and an undirected graph with several components, is not always reachable from vertex 0. Those vertices never receive times. |
| Detect an undirected cycle from every back edge, including the edge to the parent | The parent edge is how the search arrived. A cycle is a back edge to some other ancestor. |
| Recur on a graph with a long path and no explicit stack | The call stack is Θ(V) and can overflow a fixed language stack. An explicit stack has the same asymptotics and a controllable memory limit. |
Minimum hops belong to breadth-first search. A directed acyclic order belongs to topological sort, which is this finish order with the cycle test made explicit. Strongly connected components via the transpose belong to Kosaraju.
A working example
The Bash script and the Python script depth-first search from vertex 0 and record discovery time, then finish time. Edges are 0→1, 0→2, 1→3, 2→3. Both print discovery 0 1 5 2 and finish 7 4 6 3.
adj=("1 2" "3" "3" "")
disc=(-1 -1 -1 -1)
fin=(-1 -1 -1 -1)
clk=0
dfs() {
local u=$1 v
disc[u]=$clk
clk=$((clk+1))
for v in ${adj[u]}; do
if (( disc[v] < 0 )); then dfs "$v"; fi
done
fin[u]=$clk
clk=$((clk+1))
}
dfs 0
echo "${disc[*]}"
echo "${fin[*]}"
adj = [[1, 2], [3], [3], []]
disc = [-1] * 4
fin = [-1] * 4
clock = 0
def dfs(u):
global clock
disc[u] = clock
clock += 1
for v in adj[u]:
if disc[v] < 0:
dfs(v)
fin[u] = clock
clock += 1
dfs(0)
assert disc == [0, 1, 5, 2] and fin == [7, 4, 6, 3]
print(*disc)
print(*fin)
Where it is used
Depth-first search is the walk a compiler makes over a control-flow graph, the cycle check in a dependency graph, and the mark phase of a tracing garbage collector. Topological order is one of its outputs on a DAG. Breadth-first search is the walk that measures hops.
When you can drop this algorithm
Drop depth-first search when the deliverable is a shortest path. Keep it when the deliverable is a finish order, a cycle witness via a back edge, a topological order of a DAG, or the input pass of an algorithm that already says it needs discovery and finish times.
Why this stays published
We publish this so a search for depth-first search returns the discovery and finish times and the edge classes those times define. Depth-first search stamps discovery and finish times in linear time, and those intervals classify edges and expose cycles, without measuring distance.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
