Breadth First Search on Matrix in Python


In a given matrix, there are four objects to analyze the element position: left, right, bottom, and top.

Breadth First Search is nothing but finding the shortest distance between the two elements of a given 2-D Matrix. Thus, in each cell, there are four operations we can perform which can be expressed in four numerals such as,

  • '2' describes that the cell in the matrix is Source.
  • '3' describes that the cell in the matrix is Destination.
  • '1' describes that the cell can be moved further in a direction.
  • '0' describes that the cell in the matrix can not be moved in any direction.

On the basis of adobe justification, we can perform a Breadth First Search Operation on a given Matrix.

Approach to Solve this Problem

The algorithm to traverse the whole matrix and find the minimum or shortest distance between any cell using BFS is as follows:

  • First take input of row and column.
  • Initialize a matrix with the given row and column.
  • An integer function shortestDist(int row, int col, int mat[][col]) takes the row, column and matrix as the input and returns the shortest distance between the elements of the matrix.
  • Initialize the variable source and destination to find out the source as well as the destination element.
  • If the element is '3', then mark it as destination and if the element is '2', then mark it as the source element.
  • Now initialize queue data structure to implement Breadth First Search on the given matrix.
  • Insert the row and column of the matrix in the queue as pairs. Now move in the cell and find out if it is a destination cell or not. If the destination cell is having a distance minimum or less than the current cell, then update the distance.
  • Again move to another direction to find out the minimum distance of the cell from the current cell.
  • Return the minimum distance as the output.

Example

Live Demo

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
   for i in range(0, row):
      for j in range(0, col):
         if mat[i][j] == 2 :
            source_i = i
            source_j = j
         if mat[i][j] == 3 :
            destination_i = i
            destination_j = j
   dist = []
   for i in range(0, row):
      sublist = []
      for j in range(0, col):
         sublist.append(INF)
      dist.append(sublist)
   # initialise queue to start BFS on matrix
   q = queue.Queue()
   source = Node(source_i, source_j)
   q.put(source)
   dist[source_i][source_j] = 0

   # modified BFS by add constraint checks
   while (not q.empty()):
       # extract and remove the node from the front of queue
      temp = q.get()
      x = temp.row_num
      y = temp.col_num

      # If move towards left is allowed or it is the destnation cell
      if y - 1 >= 0 and (mat[x][y - 1] == 1 or mat[x][y - 1] == 3) :
      # if distance to reach the cell to the left is less than the computed previous path distance, update it
         if dist[x][y] + 1 < dist[x][y - 1] :
            dist[x][y - 1] = dist[x][y] + 1
            next = Node(x, y - 1)
            q.put(next)

      # If move towards right is allowed or it is the destination cell
      if y + 1 < col and (mat[x][y + 1] == 1 or mat[x][y + 1] == 3) :
         # if distance to reach the cell to the right is less than the computed previous path distance, update it
         if dist[x][y] + 1 < dist[x][y + 1] :
            dist[x][y + 1] = dist[x][y] + 1
            next = Node(x, y + 1)
            q.put(next);

      # If move towards up is allowed or it is the destination cell
      if x - 1 >= 0 and (mat[x - 1][y] == 1 or mat[x-1][y] == 3) :
         # if distance to reach the cell to the up is less than the computed previous path distance, update it
         if dist[x][y] + 1 < dist[x - 1][y] :
            dist[x - 1][y] = dist[x][y] + 1
            next = Node(x - 1, y)
            q.put(next)

      # If move towards down is allowed or it is the destination cell
      if x + 1 < row and (mat[x + 1][y] == 1 or mat[x+1][y] == 3) :
         # if distance to reach the cell to the down is less than the computed previous path distance, update it
         if dist[x][y] + 1 < dist[x + 1][y] :
            dist[x + 1][y] = dist[x][y] + 1
            next = Node(x + 1, y)
            q.put(next)
   return dist[destination_i][destination_j]

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)

Output

The Shortest Distance between Source and Destination is:2

Updated on: 23-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements