Python实现广度优先搜索

时间:2017-09-23 19:29:02

标签: python graph-theory breadth-first-search

我在网上找到了一个例子,然而,只返回BFS元素的序列还不足以进行计算。让我们说根是BFS树的第一级,然后它的子级是第二级,等等。我怎么知道它们在哪个级别,以及下面代码中每个节点的父级是谁(I将创建一个对象来存储其父级和树级)?

# sample graph implemented as a dictionary
graph = {'A': ['B', 'C', 'E'],
         'B': ['A','D', 'E'],
         'C': ['A', 'F', 'G'],
         'D': ['B'],
         'E': ['A', 'B','D'],
         'F': ['C'],
         'G': ['C']}

# visits all the nodes of a graph (connected component) using BFS
def bfs_connected_component(graph, start):
   # keep track of all visited nodes
   explored = []
   # keep track of nodes to be checked
   queue = [start]

   # keep looping until there are nodes still to be checked
   while queue:
       # pop shallowest node (first node) from queue
       node = queue.pop(0)
       if node not in explored:
           # add node to list of checked nodes
           explored.append(node)
           neighbours = graph[node]

           # add neighbours of node to queue
           for neighbour in neighbours:
               queue.append(neighbour)
   return explored

bfs_connected_component(graph,'A') # returns ['A', 'B', 'C', 'E', 'D', 'F', 'G']

2 个答案:

答案 0 :(得分:7)

您可以通过首先将0级分配给起始节点来跟踪每个节点的级别。然后,对于节点X的每个邻居,分配级别level_of_X + 1

此外,您的代码会多次将同一节点推送到队列中。我使用了单独的列表visited来避免这种情况。

# sample graph implemented as a dictionary
graph = {'A': ['B', 'C', 'E'],
         'B': ['A','D', 'E'],
         'C': ['A', 'F', 'G'],
         'D': ['B'],
         'E': ['A', 'B','D'],
         'F': ['C'],
         'G': ['C']}


# visits all the nodes of a graph (connected component) using BFS
def bfs_connected_component(graph, start):
    # keep track of all visited nodes
    explored = []
    # keep track of nodes to be checked
    queue = [start]

    levels = {}         # this dict keeps track of levels
    levels[start]= 0    # depth of start node is 0

    visited= [start]     # to avoid inserting the same node twice into the queue

    # keep looping until there are nodes still to be checked
    while queue:
       # pop shallowest node (first node) from queue
        node = queue.pop(0)
        explored.append(node)
        neighbours = graph[node]

        # add neighbours of node to queue
        for neighbour in neighbours:
            if neighbour not in visited:
                queue.append(neighbour)
                visited.append(neighbour)

                levels[neighbour]= levels[node]+1
                # print(neighbour, ">>", levels[neighbour])

    print(levels)

    return explored

ans = bfs_connected_component(graph,'A') # returns ['A', 'B', 'C', 'E', 'D', 'F', 'G']
print(ans)

答案 1 :(得分:2)

是的,此代码仅以广度优先的方式访问节点。对于许多应用程序来说,这本身就是一件很有用的事情(例如,在未加权的图中查找最短路径)

要实际返回BFS树,需要一些额外的工作。您可以考虑为每个节点存储子项列表,或者返回(节点,父节点)对。任何一种表示都应该允许你弄清楚树的结构。

这里要注意的另一件事是,代码使用python列表作为队列,这不是一个好主意。因为从列表中删除第一个元素,需要O(n)时间。