Warning

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

networkx.algorithms.shortest_paths.generic.all_shortest_paths

all_shortest_paths(G, source, target, weight=None, method='dijkstra')[source]

Compute all shortest paths in the graph.

Parameters:
  • G (NetworkX graph)
  • source (node) – Starting node for path.
  • target (node) – Ending node for path.
  • 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.
  • method (string, optional (default = ‘dijkstra’)) – The algorithm to use to compute the path lengths. Supported options: ‘dijkstra’, ‘bellman-ford’. Other inputs produce a ValueError. If weight is None, unweighted graph methods are used, and this suggestion is ignored.
Returns:

paths – A generator of all paths between source and target.

Return type:

generator of lists

Raises:
  • ValueError – If method is not among the supported options.
  • NetworkXNoPath – If target cannot be reached from source.

Examples

>>> G = nx.Graph()
>>> nx.add_path(G, [0, 1, 2])
>>> nx.add_path(G, [0, 10, 2])
>>> print([p for p in nx.all_shortest_paths(G, source=0, target=2)])
[[0, 1, 2], [0, 10, 2]]

Notes

There may be many shortest paths between the source and target.

See also

shortest_path(), single_source_shortest_path(), all_pairs_shortest_path()