Skip to main content

Depth-First Search (DFS) Algorithm Explained with Examples and Applications

 What is Depth-First Search (DFS)?

Depth-First Search (DFS) is a fundamental algorithm for traversing or searching tree and graph data structures. The algorithm explores as far as possible along each branch before backtracking, making it suitable for pathfinding, topological sorting, and cycle detection tasks.

DFS Algorithm Explanation

DFS can be implemented using either recursion (implicit call stack) or an explicit stack data structure. The core idea is:

  • Start at the root (or any arbitrary node for a graph).
  • Visit a node and mark it as visited.
  • Recursively or iteratively visit all the adjacent unvisited nodes.

Algorithm Steps (for Binary Tree - Recursive)

  1. Visit the current node.
  2. Recursively traverse the left subtree.
  3. Recursively traverse the right subtree.

Algorithm Steps (for General Graph - Iterative with Stack)

  1. Push the start node onto the stack and mark it as visited.
  2. While the stack is not empty:
    • Pop a node from the stack.
    • Process the node.
    • Push all unvisited adjacent nodes onto the stack and mark them visited.

Python Example Code

1. DFS for Binary Tree (Recursive)

class TreeNode:
    def __init__(self, value):
        self.val = value
        self.left = None
        self.right = None

def dfs_binary_tree(node):
    if not node:
        return
    print(node.val)
    dfs_binary_tree(node.left)
    dfs_binary_tree(node.right)

# Example Usage
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)

dfs_binary_tree(root)
    

Output:

1
2
4
5
3

2. DFS for General Graph (Iterative)

def dfs_graph(graph, start):
    visited = set()
    stack = [start]

    while stack:
        node = stack.pop()
        if node not in visited:
            print(node)
            visited.add(node)
            # Push neighbors in reverse order for correct traversal
            for neighbor in reversed(graph[node]):
                if neighbor not in visited:
                    stack.append(neighbor)

# Example Usage
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}

dfs_graph(graph, 'A')
    

Output:

A
B
D
E
F
C

Time and Space Complexity Analysis

Binary Tree

  • Time Complexity: $O(n)$ where $n$ is the number of nodes. Each node is visited exactly once.
  • Space Complexity: $O(h)$ where $h$ is the height of the tree (due to recursion stack).

General Graph

  • Time Complexity: $O(V + E)$ where $V$ is the number of vertices and $E$ is the number of edges.
  • Space Complexity: $O(V)$ to store the visited nodes and the recursion or stack.

Conclusion

Depth-First Search is a versatile and powerful tool in algorithm design. It is particularly effective when the solution involves deep paths, recursion, or backtracking. A deep understanding of DFS is crucial for solving a wide variety of algorithmic problems efficiently.

References

Comments

Popular

Understanding SentencePiece: A Language-Independent Tokenizer for AI Engineers

In the realm of Natural Language Processing (NLP), tokenization plays a pivotal role in preparing text data for machine learning models. Traditional tokenization methods often rely on language-specific rules and pre-tokenized inputs, which can be limiting when dealing with diverse languages and scripts. Enter SentencePiece—a language-independent tokenizer and detokenizer designed to address these challenges and streamline the preprocessing pipeline for neural text processing systems. What is SentencePiece? SentencePiece is an open-source tokenizer and detokenizer developed by Google, tailored for neural-based text processing tasks such as Neural Machine Translation (NMT). Unlike conventional tokenizers that depend on whitespace and language-specific rules, SentencePiece treats the input text as a raw byte sequence, enabling it to process languages without explicit word boundaries, such as Japanese, Chinese, and Korean. This approach allows SentencePiece to train subword models di...

Mastering the Byte Pair Encoding (BPE) Tokenizer for NLP and LLMs

Byte Pair Encoding (BPE) is one of the most important and widely adopted subword tokenization algorithms in modern Natural Language Processing (NLP), especially in training Large Language Models (LLMs) like GPT. This guide provides a deep technical dive into how BPE works, compares it with other tokenizers like WordPiece and SentencePiece, and explains its practical implementation with Python code. This article is optimized for AI engineers building real-world models and systems. 1. What is Byte Pair Encoding? BPE was originally introduced as a data compression algorithm by Gage in 1994. It replaces the most frequent pair of bytes in a sequence with a single, unused byte. In 2015, Sennrich et al. adapted BPE for NLP to address the out-of-vocabulary (OOV) problem in neural machine translation. Instead of working with full words, BPE decomposes them into subword units that can be recombined to represent rare or unseen words. 2. Why Tokenization Matters in LLMs Tokenization is th...

ZeRO: Deep Memory Optimization for Training Trillion-Parameter Models

In 2020, Microsoft researchers introduced ZeRO (Zero Redundancy Optimizer) via their paper "ZeRO: Memory Optimization Towards Training Trillion Parameter Models" (arXiv:1910.02054). ZeRO is a memory optimization technique that eliminates redundancy in distributed training, enabling efficient scaling to trillion-parameter models. This provides an in-depth technical breakdown of ZeRO's partitioning strategies, memory usage analysis, and integration with DeepSpeed. 1. What is ZeRO? ZeRO eliminates redundant memory copies of model states across GPUs. Instead of replicating parameters, gradients, and optimizer states across each GPU, ZeRO partitions them across all devices. This results in near-linear memory savings as the number of GPUs increases. 2. Limitations of Traditional Data Parallelism In standard data-parallel training, every GPU maintains: Model Parameters $\theta$ Gradients $\nabla \theta$ Optimizer States $O(\theta)$ This causes memory usage ...