Breadth First Search on Matrix in Python

Breadth First Search (BFS) on a matrix finds the shortest path between two cells by exploring neighbors level by level. In a 2D matrix, each cell can move in four directions: left, right, up, and down.

Matrix Cell Types

In BFS matrix problems, cells are typically represented by different values ?

  • 0 − Blocked cell (cannot move through)
  • 1 − Open cell (can move through)
  • 2 − Source cell (starting point)
  • 3 − Destination cell (target point)

BFS Algorithm for Matrix

The algorithm uses a queue to explore cells level by level ?

  1. Find source and destination positions in the matrix
  2. Initialize a distance matrix with infinite values
  3. Start BFS from source using a queue
  4. For each cell, explore all four directions
  5. Update distances if a shorter path is found
  6. Return the distance to destination

Implementation

import queue

INF = 10000

class Node:
    def __init__(self, i, j):
        self.row_num = i
        self.col_num = j

def findDistance(row, col, mat):
    source_i = 0
    source_j = 0
    destination_i = 0
    destination_j = 0
    
    # Find source and destination positions
    for i in range(row):
        for j in range(col):
            if mat[i][j] == 2:
                source_i = i
                source_j = j
            if mat[i][j] == 3:
                destination_i = i
                destination_j = j
    
    # Initialize distance matrix
    dist = [[INF for _ in range(col)] for _ in range(row)]
    
    # Initialize queue for BFS
    q = queue.Queue()
    source = Node(source_i, source_j)
    q.put(source)
    dist[source_i][source_j] = 0
    
    # BFS traversal
    while not q.empty():
        temp = q.get()
        x = temp.row_num
        y = temp.col_num
        
        # Check all four directions
        directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]  # left, right, up, down
        
        for dx, dy in directions:
            new_x, new_y = x + dx, y + dy
            
            # Check bounds and if cell is valid (1 or 3)
            if (0 <= new_x < row and 0 <= new_y < col and 
                (mat[new_x][new_y] == 1 or mat[new_x][new_y] == 3)):
                
                # Update distance if shorter path found
                if dist[x][y] + 1 < dist[new_x][new_y]:
                    dist[new_x][new_y] = dist[x][y] + 1
                    next_node = Node(new_x, new_y)
                    q.put(next_node)
    
    return dist[destination_i][destination_j]

# Example matrix
row = 5
col = 5
mat = [[1, 0, 0, 2, 1],
       [1, 0, 2, 1, 1],
       [0, 1, 1, 1, 0],
       [3, 2, 0, 0, 1],
       [3, 1, 0, 0, 1]]

answer = findDistance(row, col, mat)

if answer == INF:
    print("No Path Found")
else:
    print("The Shortest Distance between Source and Destination is:")
    print(answer)
The Shortest Distance between Source and Destination is:
2

How It Works

The algorithm starts from the source cell (value 2) and explores all reachable neighbors. It uses a queue to maintain the order of exploration, ensuring that closer cells are processed first. The distance matrix keeps track of the minimum steps needed to reach each cell.

Time and Space Complexity

  • Time Complexity: O(rows × cols) − Each cell is visited at most once
  • Space Complexity: O(rows × cols) − For the distance matrix and queue

Conclusion

BFS on a matrix efficiently finds the shortest path between two points by exploring cells level by level. This approach guarantees the minimum number of steps in unweighted grids.

Updated on: 2026-03-25T16:44:27+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements