Warning

This documents an unmaintained version of NetworkX. Please upgrade to a maintained version and see the current NetworkX documentation.

shortest_path_length

shortest_path_length(G, source=None, target=None, weight=None)[source]

Compute shortest path lengths in the graph.

Parameters:
  • G (NetworkX graph) –
  • source (node, optional) – Starting node for path. If not specified, compute shortest path lengths using all nodes as source nodes.
  • target (node, optional) – Ending node for path. If not specified, compute shortest path lengths using all nodes as target nodes.
  • weight (None or string, optional (default = None)) – If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1.
Returns:

length – If the source and target are both specified, return the length of the shortest path from the source to the target.

If only the source is specified, return a dictionary keyed by targets whose values are the lengths of the shortest path from the source to one of the targets.

If only the target is specified, return a dictionary keyed by sources whose values are the lengths of the shortest path from one of the sources to the target.

If neither the source nor target are specified return a dictionary of dictionaries with path[source][target]=L, where L is the length of the shortest path from source to target.

Return type:

int or dictionary

Raises:

NetworkXNoPath – If no path exists between source and target.

Examples

>>> G=nx.path_graph(5)
>>> print(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=nx.shortest_path_length(G) # source,target not specified
>>> p[0][4]
4

Notes

The length of the path is always 1 less than the number of nodes involved in the path since the length measures the number of edges followed.

For digraphs this returns the shortest directed path length. To find path lengths in the reverse direction use G.reverse(copy=False) first to flip the edge orientation.

See also

all_pairs_shortest_path_length(), all_pairs_dijkstra_path_length(), single_source_shortest_path_length(), single_source_dijkstra_path_length()