0

我需要从给定图表中找到所有路径。我现在可以这样做,但是我的递归代码效率不高,而且我的图表也非常复杂。因此我需要一个更好的算法。到目前为止,这是我的代码,

def findLeaves(gdict):
    # takes graph and find its leaf nodes
    leaves = []
    for endNode in gdict.iterkeys():
        if not gdict[endNode]:
            leaves.append(endNode)
    return leaves

graphPaths = {}    
def findPaths(gname, gdict, leave, path):
    # finds all noncycle paths
    if not gdict:
        return []
    temp = [node for node in gdict.iterkeys() if leave in gdict[node].keys() and node not in path] 
    if temp:
        for node in temp:
            findPaths(gname, gdict, node, [node] + path) 
    else:
        graphPaths[gname].append(path)   




    # main
    leaves = findLeaves(graph['graph'])
    graphPaths['name'] = []

    seenNodes = []
    for leave in leaves:
        findPaths(graph['name'], graph['graph'], leave, [leave])

只有一个起始节点,这使得递归函数更容易。如果以相反的顺序跟随叶子,则每个叶子都需要到达那里。起始节点是没有传入边的节点。

我有很多图表,所以我把它们放在字典里。键是图的名称。这是我的数据的示例:

graph['graph']: {
0: {1: {}}, 
1: {2: {}, 3: {}}, 
2: {3: {}}, 
3: {4: {}}, 
4: {5: {}}, 
5: {6: {}}, 
6: {7: {}}, 
7: {6: {}, 5: {}}
}

graph['name'] = nameofthegraph

这些结构取自pygraphviz,它简单地显示了来自任何节点的传出边。键是节点,值是节点的出边。但是,当我有如下非常复杂的图表时,此代码无法找到所有路径。

在此处输入图像描述

有没有更好的算法可以推荐?或者有什么方法可以优化我的复杂图形算法?

4

1 回答 1

0

为什么需要从给定图中找到所有路径?哪个上下文?我问你这个问题是因为图论在今天的计算中非常流行,可能有一种算法可以完全满足你的需求......

例如,如果最终您需要比较所有路径以找到最佳路径,您可能对“最短路径问题”感兴趣并阅读:查找两个图形节点之间的所有路径https://en.wikipedia.org/wiki /Shortest_path_problem

关于“优化”主题,python 允许您使用基于列表理解、多线程和/或子进程的代码。

您也可以尝试使用“本机图形数据库”(如 neo4js)来存储您的节点,然后使用一些内置方法,例如: http: //neo4j.com/docs/stable/cypherdoc-finding-paths.html做这项工作。

此致

于 2016-03-09T17:05:34.457 回答