简体   繁体   English

图节点中的BFS

[英]BFS in the nodes of a graph

Graph 图形

I am trying to perform BFS on this graph starting from node 16. But my code is giving erroneous output. 我正在尝试从节点16开始对该图执行BFS。但是我的代码给出了错误的输出。 Can you please help me out. 你能帮我一下吗。 Thanks. 谢谢。

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)

My output is: Output 我的输出是: 输出

path should be a list , not set since set has no order. path应该是一个list ,未set因为set没有顺序。 That should work: 那应该工作:

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)

The cause of your problem is that you are removing things from (the start of) queue while looping through it. 问题的原因是您正在循环中从queue (的开始)中删除内容。 As it loops it steps ahead, but because the element is removed from the start, the list "steps" one in the opposite direction. 在循环时,它会向前移动,但是由于从一开始就删除了该元素,因此列表沿相反的方向“步进”。 The net result is that it appears to jump 2 at a time. 最终结果似乎是一次跳2。 Here's an example: 这是一个例子:

integer_list = [1,2,3]
next_int = 4
for integer in integer_list:
   print integer
   integer_list.remove(integer)
   integer_list.append(next_int)
   next_int += 1

Produces output 产生输出

1 1个

3 3

5 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM