【发布时间】:2017-09-23 19:29:02
【问题描述】:
我在网上找到了一个例子,但是只返回BFS元素的序列是不够的。假设根是 BFS 树的第一级,然后它的子级是第二级,依此类推。从下面的代码中,我如何知道它们在哪个级别,以及每个节点的父级是谁(我将创建一个对象存储其父级和树级)?
# 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']
【问题讨论】:
-
这篇文章属于codereview网站
-
@AmiNadimi 不幸的是,它不属于代码审查。它要求新的特征(主要是遍历中节点的前身)。要求新功能在 Code Review 上是题外话。请参阅our guide for Stack Overflow users 了解更多信息。
-
理想的探索应该是一个 set(),否则这可能是 O(N*N)。 queue 也应该是一个 dequeue 以实现更快的 pop(0)
标签: python graph-theory breadth-first-search