【问题标题】:Breadth First search with adjacency matrix邻接矩阵的广度优先搜索
【发布时间】:2017-04-12 16:58:39
【问题描述】:

所以我创建了一个使用图表和起点的 bfs 遍历。它使用相邻列表中表示的图形,但我将如何更改它以使用邻接矩阵。我只需要从某个地方开始

邻接表:

{0:[1,2,3],1:[0,2,3],2:[0,1,4],3:[0,1],4:[2]}

邻接矩阵:

[ [0,1,1,1,0], 
  [1,0,1,1,0], 
  [1,1,0,0,1], 
  [1,1,0,0,0], 
  [0,0,1,0,0] ]

def bfs(graph, v):
  all = []
  Q = []
  Q.append(v)
  while Q != []:
    v = Q.pop(0)
    all.append(v)
    for n in graph[v]:
      if n not in Q and\
      n not in all:
      Q.append(n)
  return all

【问题讨论】:

  • 查看使用邻接表表示的部分。您正在迭代节点的邻居。弄清楚如何使用邻接矩阵迭代节点的邻居。

标签: python breadth-first-search adjacency-list adjacency-matrix


【解决方案1】:

我曾经遇到过类似的问题,我认为将矩阵转换为邻接列表是最简单的,即:

def matrix_to_list(matrix):
    graph = {}
    for i, node in enumerate(matrix):
        adj = []
        for j, connected in enumerate(node):
            if connected:
                adj.append(j)
        graph[i] = adj
    return graph

然后,您可以将您的规范(且已调试)广度优先搜索算法与返回的节点列表一起使用。希望对你有帮助

【讨论】:

    【解决方案2】:

    我提供此提交内容是为了帮助遇到此问题的任何人。虽然 BFS 的算法是众所周知的,但我发现在邻接矩阵(非列表)上找到 BFS 或 DFS 的 Python 实现非常困难,正如您在问题中提出的那样。

    以下实现适用于您的矩阵,如图所示。它迭代运行,并且由于它访问矩阵中的每个单元一次,它运行时间为 O(n*m),其中 n = matrix.length 和 m = matrix[0].length。在方阵上,时间为 O(n^2)。

    def bfs(matrix, row, col, visited):
        nodes = [(row, col)]
        while nodes:
            row, col = nodes.pop(0)
            # the below conditional ensures that our algorithm 
            #stays within the bounds of our matrix.
            if row >= len(matrix) or col >= len(matrix[0]) or row < 0 or col < 0:
                continue
            if (row, col) not in visited:
                if matrix[row][col] == 1:
                    visited.append((row, col))
                    nodes.append((row+1, col))
                    nodes.append((row, col+1))
                    nodes.append((row-1, col))
                    nodes.append((row, col-1))
    
    def bfs_wrapper(matrix):
        visited = []
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if (i,j) not in visited:
                    bfs(matrix, i, j, visited)
                
        return visited
    

    它返回以下内容(这是一个元组列表,其中包含矩阵中标记为 1 的单元格的行和列坐标):

    [(0, 1), (0, 2), (1, 2), (0, 3), (1, 3), (1, 0), (2, 0), (3, 0), (2, 1), (3, 1), (2, 4), (4, 2)]
    

    您可以通过将nodes.pop(0) 修改为nodes.pop() 轻松调整此方法以执行深度优先搜索。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多