Python矩阵中的广度优先搜索


在给定的矩阵中,有四个对象用于分析元素位置:左、右、下和上。

广度优先搜索就是找到给定二维矩阵的两个元素之间的最短距离。因此,在每个单元格中,我们可以执行四个操作,可以用四个数字表示为:

  • ‘2’表示矩阵中的单元格是源点。
  • ‘3’表示矩阵中的单元格是目标点。
  • ‘1’表示可以沿某个方向进一步移动该单元格。
  • ‘0’表示不能沿任何方向移动矩阵中的单元格。

基于上述说明,我们可以对给定的矩阵执行广度优先搜索操作。

解决这个问题的方法

使用BFS遍历整个矩阵并找到任何单元格之间最小或最短距离的算法如下:

  • 首先输入行和列。
  • 用给定的行和列初始化一个矩阵。
  • 一个整数函数`shortestDist(int row, int col, int mat[][col])`以行、列和矩阵作为输入,并返回矩阵元素之间的最短距离。
  • 初始化变量`source`和`destination`以找出源元素和目标元素。
  • 如果元素是‘3’,则将其标记为目标点;如果元素是‘2’,则将其标记为源元素。
  • 现在初始化队列数据结构,以在给定的矩阵上实现广度优先搜索。
  • 将矩阵的行和列作为对插入队列中。现在移动到单元格中,并找出它是否是目标单元格。如果目标单元格的距离最小或小于当前单元格,则更新距离。
  • 再次移动到另一个方向,以找出从当前单元格到该单元格的最小距离。
  • 返回最小距离作为输出。

示例

在线演示

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)

输出

The Shortest Distance between Source and Destination is:2

更新于:2021年2月23日

2K+ 次浏览

启动您的职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.