【问题标题】:finding all paths from given graph python从给定的图形python中查找所有路径
【发布时间】:2014-08-21 15:54:15
【问题描述】:

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

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

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

【问题讨论】:

  • 将此问题放在codereview.stackexchange.com 优化和提高效率
  • @sundarnatarajСундар 谢谢我不知道那个网站。 question
  • 没关系。您会在如何优化和提高效率方面获得很好的评价
  • 你的意思是找到给定图中的所有路径吗?

标签: python graph pygraphviz


【解决方案1】:

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

例如,如果最终您需要比较所有路径以找到最佳路径,您可能对“最短路径问题”感兴趣并阅读: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 来完成这项工作。

最好的问候

【讨论】:

    猜你喜欢
    • 2018-02-19
    • 2015-03-21
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    相关资源
    最近更新 更多