shortest_path_length#

shortest_path_length(G, source=None, target=None, weight=None, method='dijkstra')[源代码]#

计算图中的最短路径长度。

参数
G网络X图表
source节点,可选

路径的起始节点。如果未指定,则使用所有节点作为源节点计算最短路径长度。

target节点,可选

路径的结束节点。如果未指定,则使用所有节点作为目标节点计算最短路径长度。

weight无、字符串或函数、可选(默认值=无)

如果没有,则每条边的权重/距离/成本为1。如果是字符串,则使用该边属性作为边权重。任何不存在的边属性默认为1。如果这是一个函数,则边的权重是该函数返回的值。该函数必须恰好接受三个位置参数:一条边的两个端点和该边的边属性字典。该函数必须返回一个数字。

method字符串,可选(默认为‘Dijkstra’)

用于计算路径长度的算法。支持的选项:‘Dijkstra’、‘Bellman-Ford’。其他输入会产生ValueError。如果 weight 为NONE,则使用未加权的图形方法,并忽略此建议。

返回
长度:整型或迭代器

如果同时指定了源和目标,则返回从源到目标的最短路径长度。

如果只指定了源,则将目标键入的dict返回到从源到目标的最短路径长度。

如果只指定了目标,则将按源键控的dict返回到从该源到目标的最短路径长度。

如果既没有指定源也没有指定目标,则返回一个迭代器(source,dictionary),其中dictionary由目标键入到从源到目标的最短路径长度。

加薪
NodeNotFound

如果 source 不在 G .

NetworkXNoPath

如果在源和目标之间没有路径存在。

ValueError

如果 method 不在支持的选项中。

参见

all_pairs_shortest_path_length
all_pairs_dijkstra_path_length
all_pairs_bellman_ford_path_length
single_source_shortest_path_length
single_source_dijkstra_path_length
single_source_bellman_ford_path_length

笔记

路径的长度总是比路径中涉及的节点数少1,因为长度测量的是后面的边数。

对于有向图,这将返回最短的定向路径长度。要查找反向路径长度,请先使用g.reverse(copy=false)翻转边缘方向。

实例

>>> G = nx.path_graph(5)
>>> nx.shortest_path_length(G, source=0, target=4)
4
>>> p = nx.shortest_path_length(G, source=0)  # target not specified
>>> p[4]
4
>>> p = nx.shortest_path_length(G, target=4)  # source not specified
>>> p[0]
4
>>> p = dict(nx.shortest_path_length(G))  # source,target not specified
>>> p[0][4]
4