递归搜索networkx图
这是一个关于递归的问题(还有一点关于图形库networkx的内容):我有一个有向图,里面的节点有边,这些边有一个属性["value"],值可以是0或1(实际上就是边的权重)。
我想要递归地检查一个节点的邻居,直到某个邻居的节点不满足特定的阈值为止。比如说:
def checkAll(x):
for neighbor in graph.neighbors(x):
if neighbor is bad:
fail
else:
checkAll(neighbor)
#add all good neighbors here? This isn't working!
我在递归这块遇到了困难,基本上我觉得是因为“for”循环的写法有问题。有人能帮帮我吗?(我看过这个其他的帖子,但感觉不是特别相关?)
谢谢!
1 个回答
3
免责声明:我对networkx并不了解,但根据我对你问题的理解,也许这能帮到你:
def examine(node, neighbors_list)
for neighbor in graph.neighbors(node):
if graph[x]["neighbor"]["value"] = 1:
return
else:
neighbors_list.append(neighbor)
examine(neighbor, neighbors_list)
x = parent_node
neighbors = []
examine(x, neighbors)