Skip to main content

Search Algorithms Explained with Python

Introduction to Search Algorithms

Search algorithms are foundational tools in artificial intelligence (AI) and computer science. They enable problem-solving agents to explore complex environments, discover solutions, and make decisions. A search algorithm systematically examines possible paths in a problem space to find a solution, such as reaching a goal state from a given start state.

Broadly, search algorithms are divided into two main categories:

  • Uninformed Search Algorithms: These algorithms do not have any domain-specific knowledge beyond the problem definition. They explore the search space blindly, treating all nodes equally without estimating the direction of the goal. While often inefficient in large or complex environments, they are guaranteed to find a solution (if one exists) under certain conditions, and they form the conceptual foundation for more advanced techniques.

  • Informed Search Algorithms: Also known as heuristic search algorithms, these methods use additional information (heuristics) to evaluate the desirability of different nodes. This allows the algorithm to prioritize certain paths and reach the goal more efficiently.

This document provides detailed explanations, complexity analysis, and Python implementations of both uninformed and informed search algorithms. Each section is supported by example use cases to enhance understanding.


1. Uninformed Search Algorithms

1.1 Breadth-First Search (BFS)

Principle: Explore all the nodes at the present depth before moving on to nodes at the next depth level. It uses a queue (FIFO).

Time Complexity: $O(b^d)$
Space Complexity: $O(b^d)$

Python Code:

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])

    while queue:
        node = queue.popleft()
        if node not in visited:
            print(node, end=" ")
            visited.add(node)
            queue.extend(graph[node])

# Example usage:
graph = {
    'A' : ['B','C'],
    'B' : ['D', 'E'],
    'C' : ['F'],
    'D' : [],
    'E' : ['F'],
    'F' : []
}
bfs(graph, 'A')

1.2 Depth-First Search (DFS)

Principle: Explore as far as possible along each branch before backtracking. It uses a stack (LIFO).

Time Complexity: $O(b^d)$
Space Complexity: O(bd)

Python Code:

def dfs(graph, start, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)
    print(start, end=" ")

    for neighbor in graph[start]:
        if neighbor not in visited:
            dfs(graph, neighbor, visited)

# Example usage:
dfs(graph, 'A')

1.3 Uniform Cost Search (UCS)

Principle: Like BFS but uses cost instead of depth. It always expands the lowest cost node.

Time Complexity: $O(b^(1+C*/ε))$ where C* is the cost of the optimal solution.
Space Complexity: $O(b^(1+C*/ε))$

Python Code:

import heapq

def ucs(graph, start, goal):
    queue = [(0, start)]
    visited = set()

    while queue:
        cost, node = heapq.heappop(queue)
        if node == goal:
            print(f"Reached {goal} with cost {cost}")
            return
        if node not in visited:
            visited.add(node)
            for neighbor, weight in graph[node]:
                heapq.heappush(queue, (cost + weight, neighbor))

# Example usage:
graph_cost = {
    'A': [('B', 1), ('C', 5)],
    'B': [('D', 3), ('E', 1)],
    'C': [('F', 2)],
    'D': [],
    'E': [('F', 1)],
    'F': []
}
ucs(graph_cost, 'A', 'F')

1.4 Depth-Limited Search (DLS)

Principle: DFS with a maximum depth limit to avoid going too deep.

Time Complexity: $O(b^l)$
Space Complexity: O(bl)

Python Code:

def dls(graph, node, goal, limit):
    if node == goal:
        print(f"Found {goal}")
        return True
    if limit <= 0:
        return False
    for neighbor in graph[node]:
        if dls(graph, neighbor, goal, limit - 1):
            return True
    return False

# Example usage:
dls(graph, 'A', 'F', 3)

1.5 Iterative Deepening Depth-First Search (IDDFS)

Principle: Repeatedly apply DLS with increasing limits.

Time Complexity: $O(b^d)$
Space Complexity: O(bd)

Python Code:

def iddfs(graph, start, goal, max_depth):
    for depth in range(max_depth):
        if dls(graph, start, goal, depth):
            return True
    return False

# Example usage:
iddfs(graph, 'A', 'F', 5)

2. Informed Search Algorithms

2.1 Greedy Best-First Search

Principle: Uses heuristic function h(n) to choose the node that appears to be closest to the goal.

Time Complexity: $O(b^m)$ (where m is maximum depth of the search tree)
Space Complexity: $O(b^m)$

Python Code:

def greedy_best_first(graph, start, goal, heuristic):
    queue = [(heuristic[start], start)]
    visited = set()

    while queue:
        _, node = heapq.heappop(queue)
        if node == goal:
            print(f"Reached {goal}")
            return
        if node not in visited:
            visited.add(node)
            for neighbor in graph[node]:
                heapq.heappush(queue, (heuristic[neighbor], neighbor))

# Example usage:
heuristic = {'A': 5, 'B': 4, 'C': 2, 'D': 6, 'E': 1, 'F': 0}
graph_simple = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}
greedy_best_first(graph_simple, 'A', 'F', heuristic)

2.2 A* Search

Principle: Combines UCS and Greedy Best-First by using f(n) = g(n) + h(n), where g(n) is cost so far and h(n) is estimated cost to goal.

Time Complexity: Depends on heuristic quality, worst case $O(b^d)$
Space Complexity: $O(b^d)$

Python Code:

def a_star(graph, start, goal, heuristic):
    queue = [(heuristic[start], 0, start)]
    visited = set()

    while queue:
        f, cost, node = heapq.heappop(queue)
        if node == goal:
            print(f"Reached {goal} with total cost {cost}")
            return
        if node not in visited:
            visited.add(node)
            for neighbor, weight in graph[node]:
                g = cost + weight
                h = heuristic[neighbor]
                heapq.heappush(queue, (g+h, g, neighbor))

# Example usage:
graph_weighted = {
    'A': [('B', 1), ('C', 5)],
    'B': [('D', 3), ('E', 1)],
    'C': [('F', 2)],
    'D': [],
    'E': [('F', 1)],
    'F': []
}
heuristic2 = {'A': 5, 'B': 4, 'C': 2, 'D': 6, 'E': 1, 'F': 0}
a_star(graph_weighted, 'A', 'F', heuristic2)

3. 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...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...