从给定的图形python中查找所有路径

时间:2014-07-01 07:06:48

标签: python graph pygraphviz

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

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,它只显示来自任何节点的传出边。键是节点,值是节点的传出边。但是当我有如下非常复杂的图形时,此代码无法找到所有路径。

enter image description here

您可以建议更好的算法吗?或者有没有办法优化复杂图形的算法?

1 个答案:

答案 0 :(得分:0)

为什么需要查找给定图表中的所有路径?哪个背景? 我问你这个问题,因为图形理论在今天的计算中非常流行,可能有一种算法可以满足你的需求......

例如,如果最后您需要比较所有路径以找到最佳路径,您可能会对“最短路径问题”感兴趣并阅读:Find all paths between two graph nodes &安培; https://en.wikipedia.org/wiki/Shortest_path_problem

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

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

祝你好运

相关问题