Depth-First Search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at a designated start node (or an arbitrary node in a general graph) and explores as far as possible along each branch before backtracking.
Properties
- DFS produces a DFS forest on via the predecessor relation; in an undirected graph, each tree corresponds to a connected component.
- Each vertex receives discovery time and finish time ; the intervals satisfy the parenthesis property (either disjoint or one properly contains the other).
- Edge classification in directed graphs: tree, back, forward, cross; in undirected graphs, every non-tree edge is a back edge.
- In a DAG, ordering vertices by decreasing finish time yields a valid topological order.
Pseudocode
Formal Definition
Let be a finite directed or undirected graph and optionally a designated start vertex . Depth-First Search (DFS) explores edges out of the most recently discovered vertex that still has unexplored incident edges.
Initialization:
Procedure:
Recursive step:
Outputs:
Edge classification (directed graphs):
Parenthesis property:
Reachability (with start ):
Time and space: