shortest_simple_paths(G, source, target, weight=None)
A simple path is a path with no repeated nodes.
If a weighted shortest path search is to be used, no negative weights are allowed.
This procedure is based on algorithm by Jin Y. Yen . Finding the first $K$ paths requires $O(KN^3)$ operations.
Starting node for path
Ending node for path
If it is a string, it is the name of the edge attribute to be used as a weight.
If it is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number.
If None all edges are considered to have unit weight. Default value None.
If no path exists between source and target.
If source or target nodes are not in the input graph.
If the input graph is a Multi[Di]Graph.
A generator that produces lists of simple paths, in order from shortest to longest.
Generate all simple paths in the graph G from source to target,
starting from shortest ones.
>>> G = nx.cycle_graph(7)
... paths = list(nx.shortest_simple_paths(G, 0, 3))
... print(paths) [[0, 1, 2, 3], [0, 6, 5, 4, 3]]
You can use this function to efficiently compute the k shortest/best paths between two nodes.
>>> from itertools import isliceSee :
... def k_shortest_paths(G, source, target, k, weight=None):
... return list(
... islice(nx.shortest_simple_paths(G, source, target, weight=weight), k)
... )
... for path in k_shortest_paths(G, 0, 3, 2):
... print(path) [0, 1, 2, 3] [0, 6, 5, 4, 3]
The following pages refer to to this document either explicitly or contain code examples using this.
networkx.algorithms.simple_paths.shortest_simple_paths
Hover to see nodes names; edges to Self not shown, Caped at 50 nodes.
Using a canvas is more power efficient and can get hundred of nodes ; but does not allow hyperlinks; , arrows or text (beyond on hover)
SVG is more flexible but power hungry; and does not scale well to 50 + nodes.
All aboves nodes referred to, (or are referred from) current nodes; Edges from Self to other have been omitted (or all nodes would be connected to the central node "self" which is not useful). Nodes are colored by the library they belong to, and scaled with the number of references pointing them