Open In App

Breadth First Search (BFS) for Artificial Intelligence

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In artificial intelligence, the Breadth-First Search (BFS) algorithm is an essential tool for exploring and navigating various problem spaces. By systematically traversing graph or tree structures, BFS solves tasks such as pathfinding, network routing, and puzzle solving. This article explains core concepts of BFS, its algorithms, and practical applications in AI.

The Breadth-First Search is a traversing algorithm used to satisfy a given property by searching the tree or graph data structure. It belongs to uninformed or blind search AI algorithms as it operates solely based on the connectivity of nodes and doesn't prioritize any particular path over another based on heuristic knowledge or domain-specific information. It doesn't incorporate any additional information beyond the structure of the search space. It is optimal for unweighted graphs and is particularly suitable when all actions have the same cost. Due to its systematic search strategy, BFS can efficiently explore even infinite state spaces.

BFS Working

The graph structure of BFS allows to work as follows:

Note: Triangular marker indicates the next node to be expanded at each stage.

BFS for AI-Geeksforgeeks
  • Originally it starts at the root node, then it expands to all of its successors It systematically explores all its neighbouring nodes before moving to the next level of nodes. ( As shown in the above image, it starts from the root node A and then expands its successor B)
  • This process of extending to the root node’s immediate neighbours, then to their neighbours, and so on, lasts until all the nodes within the graph have been visited or until the specific condition is met. From the above image we can observe that after visiting the node B it moves to node C. When level 1 is completed, it further moves to the next level i.e 2 and explores node D. Then it will move systematically to node E, node F and node G. After visiting node G, it will terminate.

Key characteristics of BFS

  1. First-in-First-Out (FIFO): The FIFO queue is preferred in BFS because it is faster than a priority queue and maintains the correct node order. In BFS, new nodes deeper in the tree are added to the back of the queue, while older, shallower nodes are expanded first.
  2. Early goal test: In traditional BFS, the algorithm tracks the states reached during the search. Instead of storing all states, it keeps only those needed for an early goal test, checking if a newly generated node satisfies the goal as soon as it's created.
  3. Cost-optimal: BFS always aims to find a minimum-cost solution by prioritizing the shortest path. When it generates nodes at depth d, it has already explored all nodes at depth d−1. So, if a solution exists, BFS will find it as soon as it reaches the correct depth, making it a cost-optimal algorithm.

Breadth First Search (BFS) Algorithms in Python

1. Initialization

We define the graph using an adjacency list. The queue is a deque to allow fast appends and pops from both ends.

Screenshot-2025-07-07-115536
Graph used for this implementation

We also create a visited set to ensure each node is processed only once, and traversal_order to store the BFS path.

Python
from collections import deque

# Graph as an adjacency list
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': [],
    'F': []
}

# Initialize the queue, visited set, and result list
queue = deque()         
visited = set()          
traversal_order = []     

2. Enqueue the Starting Node

This step starts the BFS process. We:

  • Enqueue the starting node A
  • Mark A as visited - Queue: [A], Visited: {A}
Python
start_node = 'A'
queue.append(start_node)   # Enqueue node A
visited.add(start_node)    # Mark A as visited

3. BFS Loop

This loop processes nodes in FIFO order:

  • Dequeue the current node.
  • Add it to the traversal result.
  • For each neighbor: If not already visited, enqueue it and mark it visited.

It automatically handles:

  • Dequeue A -> Enqueue B, C -> Queue: [B, C]
  • Dequeue B -> Enqueue D, E -> Queue: [C, D, E]
  • Dequeue C -> Enqueue F -> Queue: [D, E, F]
  • Dequeue D, E, F -> No new nodes -> Queue becomes empty
Python
while queue:
    current = queue.popleft()            
    traversal_order.append(current)      

    for neighbor in graph[current]:      
        if neighbor not in visited:
            queue.append(neighbor)       # Enqueue unvisited neighbor
            visited.add(neighbor)        # Mark it visited

4. Final Traversal Order

Python
print("\nFinal Traversal Order:")
print(" → ".join(traversal_order))

Output:

Final Traversal Order: A → B → C → D → E → F

You can get the full code from here.

Breadth-First Search in Robot Pathfinding

The Breadth-first-search is a method of uninformed search, so our example’s robot does not use any information about how far our robot has traveled from its initial state nor how far the robot is from the goal. Using BFS we begin by positioning the robot at the root node, now it starts looking for the goal by expanding all of neighbor nodes (successors) of the root node.. Here, successors of a node are said to hold all the allowable directions that the robot could travel next. Nodes that are already visited by the robots are not considered as successors. Take a look at the below picture, the robot can travel 8 possible directions.

robot

Step 1: The initial step in the Breath-first-search algorithm is to begin with the starting node. In this case, the ‘R’ serves as a starting node, so we visit node R first. Additionally, we add the visited node to the FIFO queue. By adding node ‘R’ to the queue, we ensure it is explored in the subsequent steps of the algorithm.

Initial-node
Initial node is visited first

Step 2: We dequeue node R from the FIFO queue to expand it. Upon expansion, we discover a successor node labeled S, representing the direction south. Since node S has been visited, it is now enqueued in the FIFO queue for further exploration.

FIRST-STEP
Node R is expanded

Step 3: Similarly, we dequeue the S from the FIFO queue to expand it. We gain two more successor nodes that are labeled as S and E representing the direction of South and South east. These directions are the paths that our robot tends to traverse next. The visited nodes such as S and E are enqueued in the FIFO queue to avoid revisiting them.

Second

Step 4: Again S is dequeued from the queue and expanded by gaining the other two successors such as S and E. It is also enqueued to the FIFO queue.

E

Step 5: Here, we dequeue the node E which leads to the expansion of two more nodes called S and N representing East and North East, respectively. As in the previous steps, we enqueue the newly visited nodes for further exploration.

Fourth

Step 6: The FIFO queue continues until the goal is found. Once the goal is discovered, the path that leads to a goal node is traced back up the tree so that it maps out the directions for the robot to reach the goal. In our example, let's say that the goal node E was found when node SE was expanded. By traversing back up to the tree we can easily trace the path that the robot needs to follow. In this case, the robot needs to begin from the south then move to the southeast, and then finally head to the east to reach the goal.

Practical Implementations of BFS in Pathfinding of Robots

Consider the below example, depicting the scenario where a robot seeks to navigate to its goal. Initially, the robot expands its successors that evaluate the possible moves to progress towards its destination. It is essential to note the presence of obstacles that may impede the robot's path as it traverses through the nodes. Let’s now understand the concept of pathfinding stepwise.

Step 1: Create a Node a class for the search tree

The Node class represents a node in a search tree that contains the states or grid coordinates of the robots.

Python
class Node:
    def __init__(self, state, parent=None, action=None):
        self.state = state
        self.parent = parent
        self.action = action

Step 2: Create a class for GridProblem and Node

The GridProblem class represents the problem of pathfinding on a grid. It contains attributes for the initial state, goal state, and obstacles on the grid. The three typical methods are fitted in the code such as

  1. is_goal : This method checks if the given state is the goal state.
  2. is_valid_cell : This functions checks that a cell is valid to move or obstacles
  3. expand : This method is in charge of generating child nodes (states) from the given parent node by considering obstacles and grid boundaries.
Python
from collections import deque

class GridProblem:
    def __init__(self, initial_state, goal_state, grid):
        self.initial_state = initial_state
        self.goal_state = goal_state
        self.grid = grid

    def is_goal(self, state):
        return state == self.goal_state

    def is_valid_cell(self, row, col):
        return 0 <= row < len(self.grid) and 0 <= col < len(self.grid[0]) and self.grid[col][row] == 0

    def expand(self, node):
        row, col = node.state
        children = []
        for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            new_row, new_col = row + dr, col + dc
            if self.is_valid_cell(new_row, new_col):
                child_state = (new_row, new_col)
                child_node = Node(child_state, parent=node)
                children.append(child_node)
        return children

Step 3: Function to reconstruct the Solutions path

Define the function to reconstruct the solution path and print the path

Python
def reconstruct_path(node):
    path = []
    while node:
        path.append(node.state)
        node = node.parent
    return list(reversed(path))


# Function to print the complete path
def print_complete_path(path):
    for step, point in enumerate(path):
        print("Step {}: {}".format(step, point))

Step 4: Define the Traversal Algorithms

This the most important parts of the solutions. We we use the same breadth_first_search algorithm function which is defined above.

Step 5: Example Usage

In this example, we initialize the initial state such as (0,0) and goal state as (0,6) and obstacles on the grid. It creates a GridProblem instance with these parameters and when it calls the BREATH_FIRST_SEARCH function it finds the solution for the problem instance. If it can't find the solution for the problem instance it returns No solution found.

Python
# Example usage and grid definition
"""
    1 : Denotes the obstacles
    0 : Empty space or a non-obstacle cell in the grid
"""
grid = [
    [0, 1, 0, 0, 1, 0, 0],
    [0, 1, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0],
    [0, 0, 1, 0, 1, 0, 0],
    [0, 0, 1, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0]
]

# Define initial and goal states
initial_state = (0, 0)
goal_state = (6, 0)

# Define the problem instance
problem = GridProblem(initial_state, goal_state, grid)

# Perform breadth-first search to find a solution
solution_node = breadth_first_search(problem)

# Print solution if found
print('!! Reached the Goal!!' if solution_node else None)
if solution_node:
    print("Solution found!")
    solution_path = reconstruct_path(solution_node)
    print("Complete Path:")
    print_complete_path(solution_path)
else:
    print("No solution found")

Grid with Obstacles

Robot (0,0)

Block

(2,0)

(3,0)

Block

(5,0)

Goal

(0,1)

Block

(2,1)

(3,1)

Block

(5,1)

(6,1)

(0,2)

(1,2)

(2,2)

(3,2)

Block

(5,2)

(6,2)

(0,3)

(1,3)

Block

(3,4)

Block

(5,3)

(6,3)

(0,4)

(1,4)

Block

(3,5)

(4,4)

(5,4)

(6,4)

(0,5)

(1,5)

Block

(3,6)

(4,5)

(5,5)

(6,5)

(0,6)

(1,6)

Block

(3,6)

(4,6)

(5,6)

(6,6)

Output:

!! Reached the Goal!!
Solution found!
Complete Path:
Step 0: (0, 0)
Step 1: (0, 1)
Step 2: (0, 2)
Step 3: (1, 2)
Step 4: (2, 2)
Step 5: (3, 2)
Step 6: (3, 3)
Step 7: (3, 4)
Step 8: (4, 4)
Step 9: (5, 4)
Step 10: (6, 4)
Step 11: (6, 3)
Step 12: (6, 2)
Step 13: (6, 1)
Step 14: (6, 0)

Output explanation

  1. We first start at the initial position (0,0), it is where the robot begins its exploration.
  2. The robot moves south along below row such as (0,1), and (0,2).
  3. Now, the robot moves east along the column to the position of (1,2).
  4. The robot follows a path to the east (2,2), and (3,2), then south (3,3), and again (3,4).
  5. Again, the robot moves east to towards (4,4), (5,4) and (6,4).
  6. Now the robot moves towards the North along row from (6,4) to (6,3),(6,2),(6,1) and (6,0).
  7. Finally, the robot reaches the goal node i.e (6,0).
Breadth-First-Search-(BFS)-for-Artificial-Intelligence

The output indicates that the Breadth_First_Search algorithm successfully found a solution to the pathfinding problem. In this case, the goal state is (6,0) that represents the destination that the robot needs to reachPractical use cases in AI.

You can get the full code from here.

Applications of BFS in Artificial Intelligence

1. Pathfinding Algorithms

Breadth-First Search (BFS) is commonly used for finding the shortest path in unweighted graphs. By exploring nodes level by level, BFS guarantees that the first time it reaches the destination, it has found the shortest possible route. Example: BFS is useful in maze-solving, robotic movement, and route planning. For instance, in simple route navigation systems like those used by Google Maps (when weights aren’t involved), BFS-like techniques help determine the optimal path.

2. Web Crawling

BFS is fundamental in web crawling, where pages are systematically visited based on their link depth. Starting from a root URL, it explores all hyperlinks on a page before moving deeper into linked pages. This strategy ensures organized, level-wise data collection and is particularly useful for building search engine indexes or extracting structured data from websites.

3. Social Network Analysis

In platforms like LinkedIn or Facebook, BFS is employed to analyze relationships, such as identifying degrees of separation, finding mutual friends, or tracing connection paths between users. It’s also used to locate key influencers or clusters within a network, offering insights into complex social structures by traversing user connections in a breadth-wise manner.

4. AI in Games

BFS is often used in game artificial intelligence for exploring possible states or determining optimal moves. Example: In games like Pac-Man, BFS helps compute the shortest path for ghosts to chase Pac-Man or for Pac-Man to escape. Similarly, in puzzle-solving games or board games like Sudoku and chess, BFS ensures a thorough and fair exploration of all possible actions.

Advantages and Disadvantages of BFS

Advantages of BFS

  • Shortest Path: Always finds the shortest path in unweighted graphs.
  • Simple: Easy to understand and implement with a queue.
  • Versatile: Used in web crawling, social networks, AI, etc.
  • Systematic: Explores nodes level by level without missing any.

Disadvantages of BFS

  • High Memory: Needs to store all nodes at each level.
  • Slow for Deep Nodes: Explores many shallow nodes before deep ones.
  • Not for Weighted Graphs: Doesn't handle edge weights; Dijkstra’s is better.

Similar Reads