BFS在图的节点中

时间:2016-11-30 09:52:04

标签: python algorithm graph networkx breadth-first-search

Graph

我正在尝试从节点16开始在此图上执行BFS。但是我的代码提供了错误的输出。你能帮帮我吗?感谢。

visited_nodes = set()
queue = [16]
pardaught = dict()
exclu = list()
path = set()
for node in queue:
    path.add(node)
    neighbors = G.neighbors(node)
    visited_nodes.add(node)
    queue.remove(node)
    queue.extend([n for n in neighbors if n not in visited_nodes])

newG = G.subgraph(path)
nx.draw(newG, with_labels=True)

我的输出是: Output

2 个答案:

答案 0 :(得分:2)

path应该是list,而不是set,因为set没有订单。 这应该有效:

visited_nodes = set()
path = []
queue = [16]

while queue:
    node = queue.pop(0)
    visited_nodes.add(node)
    path.append(node)

    for neighbor in G.neighbors(node):
        if neighbor in visited_nodes:
            continue
        queue.append(neighbor)

答案 1 :(得分:2)

问题的原因是你在循环播放时从({1}}开始删除了东西。因为它循环前进,但是因为元素从开始被移除,所以列表以相反的方向“步进”。最终结果是它似乎一次跳2。这是一个例子:

queue

生成输出

  

1

     

3

     

5