Articles / AI · Part 13

Breadth-First Search (BFS) in Artificial Intelligence

Learn Breadth-First Search (BFS) in Artificial Intelligence. Understand its level-by-level exploration, queue and FIFO principle, Python implementation, dry run, complexity, advantages, limitations, and real-world applications.

Breadth-First Search (BFS) in Artificial Intelligence

Imagine you are searching for a friend in a large network of people. You know your friend’s name, but you don’t know who knows them.

Would you start following one person’s entire circle of friends before checking anyone else? Probably not.

A more sensible approach would be to first check everyone you know directly. If you don’t find your friend, you would check the people they know. Then you would move to the next level.

This approach helps you explore nearby possibilities before moving further.

In Artificial Intelligence, this idea is used in an important search algorithm called Breadth-First Search (BFS).

BFS is one of the fundamental uninformed search algorithms. It explores a search tree level by level, making sure that all nodes at one depth are considered before moving to the next.

Let’s understand how it works, why it uses a queue, and how we can implement it using Python.

Breadth-First Search (BFS) is an uninformed search algorithm that explores all neighbouring nodes at the current depth before moving to nodes at the next depth.

In simple words, BFS searches broadly before searching deeply.

It begins with the initial node, explores all its immediate neighbours, then explores the neighbours of those nodes, and continues until the goal is found or there are no more nodes to explore.

Consider this simple search tree:

             A
          /  |  \
         B   C   D
        / \     / \
       E   F   G   H

If we start the search from node A, BFS explores the nodes in this order:

A → B → C → D → E → F → G → H

Notice that BFS completes one level before moving to the next.

  • Level 0: A
  • Level 1: B, C, D
  • Level 2: E, F, G, H

This is the central idea behind Breadth-First Search.

1. How Does BFS Work?

To understand BFS, imagine exploring the same tree step by step.

We begin at node A.

Step 1: Start at A

A is the initial node. We visit it and add its neighbouring nodes to the queue.

Step 2: Explore B

B is the first node in the queue. We remove it and visit it. Its children, E and F, are added to the queue.

Step 3: Explore C

Next, we remove C from the queue. It has no children in this example.

Step 4: Explore D

We remove D and add its children, G and H, to the queue.

Step 5: Explore the remaining nodes

We now visit E, F, G, and H in that order.

The complete traversal is:

A → B → C → D → E → F → G → H

The important thing to notice is that BFS never moves to the next level while unvisited nodes remain at the current level.

2. Why Does BFS Use a Queue?

This is one of the most important things to understand about BFS.

A queue is a linear data structure that follows the principle of First In, First Out (FIFO).

It means that the element added first is removed first.

Think of a queue of people waiting at a ticket counter. The person who arrives first is served first.

BFS uses the same principle.

When a node is explored, its unvisited neighbours are added to the back of the queue. The algorithm always removes the node at the front.

This ensures that nodes closer to the starting point are explored before nodes that are further away.

Consider the queue during our previous example:

Step Node explored Queue after adding neighbours
Start — A
1 A B, C, D
2 B C, D, E, F
3 C D, E, F
4 D E, F, G, H
5 E F, G, H
6 F G, H
7 G H
8 H Empty

The queue controls the order of exploration. Without it, BFS would not maintain its level-by-level behaviour.

3. BFS Algorithm

Now that we understand the working of BFS, let’s look at its general algorithm.

Input: A graph or search tree and a starting node.

Output: The nodes visited in breadth-first order.

The basic steps are:

  1. Create an empty queue.
  2. Add the starting node to the queue.
  3. Mark the starting node as visited.
  4. While the queue is not empty:
    • Remove the front node.
    • Process or visit that node.
    • Examine its neighbouring nodes.
    • Add every unvisited neighbour to the queue and mark it as visited.
  5. Stop when the queue becomes empty, or when the goal is found if performing a goal-directed search.

The visited set is important when working with graphs because a graph may contain cycles. It prevents the algorithm from visiting the same node repeatedly.

4. Implementing BFS Using Python

Let’s implement Breadth-First Search using Python.

We will represent the graph using an adjacency list. Each node will store a list of its neighbouring nodes.

from collections import deque

graph = {
    'A': ['B', 'C', 'D'],
    'B': ['E', 'F'],
    'C': [],
    'D': ['G', 'H'],
    'E': [],
    'F': [],
    'G': [],
    'H': []
}

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

    visited.add(start)

    while queue:
        node = queue.popleft()
        print(node, end=" ")

        for neighbour in graph[node]:
            if neighbour not in visited:
                visited.add(neighbour)
                queue.append(neighbour)

bfs(graph, 'A')

Output: A B C D E F G H

Let’s understand the important parts.

1. Importing deque

from collections import deque

We use deque to implement the queue efficiently. It supports adding elements at the back and removing elements from the front.

2. Creating the visited set

visited = set()

This set stores the nodes that have already been discovered. It prevents repeated visits.

3. Creating the queue

queue = deque([start])

The starting node is added to the queue.

4. Removing a node

node = queue.popleft()

This removes the first node from the queue, following FIFO order.

5. Exploring neighbours

for neighbour in graph[node]:
    if neighbour not in visited:
        visited.add(neighbour)
        queue.append(neighbour)

The algorithm checks each neighbour. If it has not been visited, it marks it as visited and adds it to the queue.

This process continues until the queue becomes empty.

5. Dry Run of BFS

A dry run means executing an algorithm manually, step by step, to understand how its variables and data structures change.

Let’s perform a dry run using our graph.

Starting node: A

Step Current node Queue after processing Visited nodes
1 A B, C, D A, B, C, D
2 B C, D, E, F A, B, C, D, E, F
3 C D, E, F A, B, C, D, E, F
4 D E, F, G, H A, B, C, D, E, F, G, H
5 E F, G, H A, B, C, D, E, F, G, H
6 F G, H A, B, C, D, E, F, G, H
7 G H A, B, C, D, E, F, G, H
8 H Empty A, B, C, D, E, F, G, H

After all eight nodes have been explored, the queue becomes empty and the algorithm terminates.

The traversal order is:

A → B → C → D → E → F → G → H

6. BFS for Finding a Goal

So far, we have used BFS to visit every reachable node. But in AI search problems, we often want to find a particular goal.

Let’s modify our Python implementation to stop when the goal is found.

from collections import deque

def bfs_search(graph, start, goal):
    visited = {start}
    queue = deque([[start]])

    while queue:
        path = queue.popleft()
        node = path[-1]

        if node == goal:
            return path

        for neighbour in graph[node]:
            if neighbour not in visited:
                visited.add(neighbour)
                queue.append(path + [neighbour])

    return None


result = bfs_search(graph, 'A', 'G')

print("Path:", result)

Output:

Path: ['A', 'D', 'G']

This version stores complete paths in the queue. When it reaches the goal, it returns the path used to reach it.

In larger problems, storing complete paths in every queue entry can consume extra memory. A more memory-efficient implementation stores parent information and reconstructs the path after finding the goal.

7. Completeness and Optimality of BFS

BFS has two important properties.

Completeness

BFS is complete when the branching factor is finite. This means it will find a solution if one exists at a finite depth.

Optimality

BFS finds the shallowest goal node. When every action has the same cost, the shallowest solution is also the least-cost solution.

However, if actions have different costs, the shallowest path may not be the cheapest path. In that situation, Uniform Cost Search is more appropriate.

8. Time and Space Complexity of BFS

To understand how BFS performs as a problem becomes larger, we use time and space complexity.

Let:

  • (b) = branching factor
  • (d) = depth of the shallowest goal

In the worst case, BFS explores nodes up to the goal depth and may generate nodes at the next level.

Its approximate time complexity is:

\[
O(b^{d+1})
\]

Its space complexity is also:

\[
O(b^{d+1})
\]

This means that both the number of nodes explored and the memory required can grow rapidly as the branching factor or goal depth increases.

This is one of the biggest limitations of BFS.

It can find a shallow solution reliably, but storing many nodes in memory can become expensive for large search problems.

9. Advantages and Limitations of BFS

Advantages

  • It is complete when the branching factor is finite.
  • It finds the shallowest solution.
  • It is optimal when all actions have equal cost.
  • Its level-by-level approach makes its behaviour easy to understand.
  • It is useful for finding shortest paths in unweighted graphs.

Limitations

  • It can consume a large amount of memory.
  • It may explore many unnecessary nodes before reaching the goal.
  • It becomes expensive when the branching factor is large.
  • It does not guarantee the lowest-cost path when action costs differ.

10. Real-World Applications of BFS

BFS is not limited to theoretical search trees. It is also useful in practical computing problems.

1. Social Networks

BFS can identify people within a certain number of connections. For example, it can find friends of friends in a social network.

2. Shortest Paths in Unweighted Graphs

It can find the path with the fewest edges between two nodes when all edges have equal cost.

3. Web Crawling

A web crawler can explore pages by visiting links from a starting page and then discovering links from those pages.

4. Network Broadcasting

BFS-like traversal can help explore network connections and reach devices in successive levels.

5. Puzzle Solving

BFS can explore possible puzzle states and find the solution requiring the fewest moves when each move has equal cost.

Conclusion

Breadth-First Search is one of the most important uninformed search algorithms in Artificial Intelligence.

It explores the search space level by level, using a queue to ensure that the earliest discovered nodes are processed first.

We have seen how BFS works, why it uses the FIFO principle, how to implement it in Python, and how to trace its execution through a dry run.

Its biggest strength is that it can find the shallowest solution and, when all actions have equal cost, the shortest path in terms of number of steps.

However, its memory requirements can become very large as the search space grows.

This raises an interesting question: what if we want to explore a search space without storing so many nodes at once?

In the next article, we will study Uniform Cost Search (UCS), an algorithm that selects paths based on their total cost rather than simply their depth.

Quick quiz

5 questions
What is the main principle of BFS?
Which data structure does BFS use?
What does FIFO mean?
When does BFS guarantee the shortest path?
What is one major limitation of BFS?

Keep a copy

Read offline as a printout or PDF.

farhanpaal.com

Keep reading

AI · Part 23

Gradient Descent in Artificial Intelligence

Understand how Gradient Descent helps machine learning models learn by reducing their errors. Explore its mathematical formula, Python implementation, learning rate, types,…

8 min read
AI · Part 8

Rationality and the Concept of a Rational Agent.

Understand rationality in Artificial Intelligence and how rational agents select actions using performance measures, percept sequences, built-in knowledge, and available information.

8 min read

Ask Farhan

Ask anything about Farhan