Definition
Depth-First Search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (or any arbitrary node in case of a graph) and explores as far as possible along each branch before backtracking.
Constraints
- Graph can be directed or undirected
- May need cycle detection for certain applications
- For disconnected graphs, needs to be run on each component
Step-by-step explanation
Arguments:
- Graph representation -
graph
- Starting node -
start
- Visited set (optional) -
visited
Explanation:
- Mark the current node as visited
- Process the current node (print, store, etc.)
- For each adjacent node of the current node:
- If the node hasn't been visited, recursively perform DFS on it
- The algorithm explores as deep as possible before backtracking
Returns:
Depends on implementation - can return traversal order, connected components, or other graph properties