简体   繁体   English

查找方向图中包含指定节点的长度为n的所有循环的最快方法

[英]Fastest way to find all cycles of length n containing a specified node in a directional graph

I have a large directional graph with ~250 nodes and ~750 weighted edges. 我有一个约250个节点和750个加权边的大方向图。 I'm looking for a way to find all cycles of length n containing a specified node. 我正在寻找一种找到包含指定节点的长度为n的所有循环的方法。 For instance, if I want all cycles of length n containing node A in a directional graph DG , I would do: 例如,如果我要在方向图DG包含节点A所有长度为n循环,我将执行以下操作:

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? 有没有更好的解决方案来解决这个问题?

For those interested, I adapted Joel's answer here to create a much more efficient way to do this. 对于那些感兴趣的人,我在这里修改了Joel的答案以创建一种更有效的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM