[英]Find the number of cycles in a graph (Python)
I have to find the number of cycles in a graph. 我必须在图中找到循环数。
I have a set of nodes connected to each other which have the following structure: 我有一组相互连接的节点,这些节点具有以下结构:
class Node:
def __init__(self, id, value):
self.divergencePoint = 0
self.convergencePoint = 0
self.id = id
self.value = value
self.parents = []
self.children = []
I have successfully created the graph and the fields divergencePoint and convergencePoint are set to 1 if it is a convergence point or a divergence point. 我已经成功创建了图形,并且如果它是一个收敛点或一个分歧点,则将divergencePoint和ConvergencePoint字段设置为1。
Now how can I detect the cycles ? 现在如何检测周期?
Since you've already found the convergence and divergence points, this is an easy task. 由于您已经找到了收敛点和分歧点,因此这很容易。 You start at a divergence point and recursively add its children to the diamond until you encounter a convergence point. 您从发散点开始,然后将其子级递归添加到菱形,直到遇到会合点。
for node in divergence_nodes:
diamond= {node}
queue= node.children[:]
while queue:
node= queue.pop()
if node in diamond:
continue
diamond.add(node)
if not node.convergencePoint:
queue+= node.children
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.