networkx shortest_path(G [,source,target,weight])函数的源算法

时间:2014-07-28 20:24:26

标签: python algorithm graph networkx shortest-path

我正在使用networkx做一些工作,并使用了两个最短路径算法,即:

 shortest_path(G[, source, target, weight]) 
 dijkstra_path(G, source, target[, weight])

我知道dijkstra_path(G, source, target[, weight])函数是基于dijkstra的最短路径算法。我想知道shortest_path(G[, source, target, weight])函数所基于的源算法。我需要它,因为我必须报告我使用的算法。我搜索了一些像Networkx - Shortest path lengthAll shortest paths for weighted graphs with networkx?这样的stackoverflow页面 {{3}}但他们并没有完全回答我的问题,我也仔细查看了关于google的网络文档和其他文章,并且找不到答案。有人可以帮我提供这些信息。谢谢

2 个答案:

答案 0 :(得分:3)

这是广度优先搜索算法(BFS)。以下是单源问题的完整NetworkX代码。它还用于全对最短路径计算。对于源 - 目标最短路径,使用双向版本的BFS。这个文档没有很好的记录,但文档和代码位于http://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html

def single_source_shortest_path(G,source,cutoff=None):
    level=0                  # the current level
    nextlevel={source:1}       # list of nodes to check at next level
    paths={source:[source]}  # paths dictionary  (paths to key from source)
    if cutoff==0:
        return paths
    while nextlevel:
        thislevel=nextlevel
        nextlevel={}
        for v in thislevel:
            for w in G[v]:
                if w not in paths:
                    paths[w]=paths[v]+[w]
                    nextlevel[w]=1
        level=level+1
        if (cutoff is not None and cutoff <= level):  break
    return paths

答案 1 :(得分:1)

这也是Dijkstra为#34;典型的&#34; case,查看源代码,这表明它只是一些条件子句:

http://networkx.lanl.gov/_modules/networkx/algorithms/shortest_paths/generic.html#shortest_path

 ...
 if source is None:
        if target is None:
            if weight is None:
                paths=nx.all_pairs_shortest_path(G)
            else:
                paths=nx.all_pairs_dijkstra_path(G,weight=weight)
        else:
            raise nx.NetworkXError(\
                "Target given but no source specified.")
    else: # source specified
        if target is None:
            if weight is None:
                paths=nx.single_source_shortest_path(G,source)
            else:
                paths=nx.single_source_dijkstra_path(G,source,weight=weight)
        else:
            # shortest source-target path
            if weight is None:
                paths=nx.bidirectional_shortest_path(G,source,target)
            else:
                paths=nx.dijkstra_path(G,source,target,weight)

    return paths