0

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.

Now how can I detect the cycles ?

Gaulthier
  • 320
  • 7
  • 16

1 Answers1

0

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
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149