gpt4 book ai didi

python - 图节点中的 BFS

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:21:56 26 4
gpt4 key购买 nike

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

最佳答案

问题的原因是您在循环遍历 queue 时从(开始的)中删除了一些东西。当它循环时,它会向前移动,但是因为元素从一开始就被删除了,所以列表会向相反的方向“移动”一个。最终结果是它似乎一次跳了 2 个。这是一个例子:

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

产生输出

1

3

5

关于python - 图节点中的 BFS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40885112/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com