2

I have a large directional graph with ~250 nodes and ~750 weighted edges. I'm looking for a way to find all cycles of length n containing a specified node. For instance, if I want all cycles of length n containing node A in a directional graph DG, I would do:

import networkx as nx
DG = nx.DiGraph() # assume this is a large graph
cycles = nx.simple_cycles(DG)
n = 4
node = 'A'
relevant_cycles = []
for cycle in cycles:
    if len(cycle) == n and node in cycle:
        relevant_cycles.append(cycle)

However, this is extremely slow for the large graph I'm dealing with. Is there a better solution to this problem?

user3294195
  • 1,748
  • 1
  • 19
  • 36

1 Answers1

2

For those interested, I adapted Joel's answer here to create a much more efficient way to do this.

def findPaths(G,u,n):
    if n==0:
        return [[u]]
    paths = [[u]+path for neighbor in G.neighbors(u) for path in findPaths(G,neighbor,n-1)]
    return paths

def find_cycles(G,u,n):
    paths = findPaths(DG,u,n)
    return [tuple(path) for path in paths if (path[-1] == u) and sum(x ==u for x in path) == 2]

cycles = find_cycles(DG,'A',4) # example usage
user3294195
  • 1,748
  • 1
  • 19
  • 36