a
IlX`h
@sndZddlmZddlmZmZddlmZddlZ ddl
mZddlm
Z
gdZd d
ZdDdd
ZdEddZdFddZdGddZdHddZdIddZdJddZdKddZdLddZdMddZdNd d!ZdOd"d#ZdPd$d%ZdQd&d'ZdRd)d*ZdSd,dZdTd.d/Z dUd0d1Z!dVd2d3Z"dWd4d5Z#dXd6d7Z$dYd8d9Z%dZd:d;Z&d[dd?Z(d]d@dAZ)d^dBdCZ*dS)_z.
Shortest path algorithms for weighed graphs.
)deque)heappushheappop)countN)generate_unique_node)_build_paths_from_predecessors)
dijkstra_pathdijkstra_path_lengthbidirectional_dijkstrasingle_source_dijkstrasingle_source_dijkstra_path"single_source_dijkstra_path_lengthmulti_source_dijkstramulti_source_dijkstra_path!multi_source_dijkstra_path_lengthall_pairs_dijkstraall_pairs_dijkstra_pathall_pairs_dijkstra_path_length!dijkstra_predecessor_and_distancebellman_ford_pathbellman_ford_path_lengthsingle_source_bellman_fordsingle_source_bellman_ford_path&single_source_bellman_ford_path_lengthall_pairs_bellman_ford_path"all_pairs_bellman_ford_path_length%bellman_ford_predecessor_and_distancenegative_edge_cyclegoldberg_radzikjohnsoncs,trSr fddSfddS)a_Returns a function that returns the weight of an edge.
The returned function is specifically suitable for input to
functions :func:`_dijkstra` and :func:`_bellman_ford_relaxation`.
Parameters

G : NetworkX graph.
weight : string or function
If it is callable, `weight` itself is returned. If it is a string,
it is assumed to be the name of the edge attribute that represents
the weight of an edge. In that case, a function is returned that
gets the edge weight according to the specified edge attribute.
Returns

function
This function returns a callable that accepts exactly three inputs:
a node, an node adjacent to the first one, and the edge attribute
dictionary for the eedge joining those nodes. That function returns
a number representing the weight of an edge.
If `G` is a multigraph, and `weight` is not callable, the
minimum edge weight over all parallel edges is returned. If any edge
does not have an attribute with key `weight`, it is assumed to
have weight one.
cstfddDS)Nc3s]}dVqdS)Nget).0attrweight/Users/cmdms/OneDriveUOB/Development/Projects/2021/samconsensusv3/env/lib/python3.9/sitepackages/networkx/algorithms/shortest_paths/weighted.py Mz5_weight_function....)minvaluesuvdr%r'r(Mr*z"_weight_function..csdS)Nr r!)r.r/datar%r'r(r1Nr*)callableZ
is_multigraph)Gr&r'r%r(_weight_function)s
r5r&cCstd\}}S)aReturns the shortest weighted path from source to target in G.
Uses Dijkstra's Method to compute the shortest weighted path
between two nodes in a graph.
Parameters

G : NetworkX graph
source : node
Starting node
target : node
Ending node
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

path : list
List of nodes in a shortest path.
Raises

NodeNotFound
If `source` is not in `G`.
NetworkXNoPath
If no path exists between source and target.
Examples

>>> G = nx.path_graph(5)
>>> print(nx.dijkstra_path(G, 0, 4))
[0, 1, 2, 3, 4]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None.
So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
will find the shortest red path.
The weight function can be used to include node weights.
>>> def func(u, v, d):
... node_u_wt = G.nodes[u].get("node_weight", 1)
... node_v_wt = G.nodes[v].get("node_weight", 1)
... edge_wt = d.get("weight", 1)
... return node_u_wt / 2 + node_v_wt / 2 + edge_wt
In this example we take the average of start and end node
weights of an edge and add it to the weight of the edge.
The function :func:`single_source_dijkstra` computes both
path and lengthofpath if you need both, use that.
See Also

bidirectional_dijkstra(), bellman_ford_path()
single_source_dijkstra()
targetr&rr4sourcer7r&lengthpathr'r'r(rQsLrc
CsrkrdSt}td}z
WStyl}z$tddWYd}~n
d}~00dS)a4Returns the shortest weighted path length in G from source to target.
Uses Dijkstra's Method to compute the shortest weighted path length
between two nodes in a graph.
Parameters

G : NetworkX graph
source : node label
starting node for path
target : node label
ending node for path
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

length : number
Shortest path length.
Raises

NodeNotFound
If `source` is not in `G`.
NetworkXNoPath
If no path exists between source and target.
Examples

>>> G = nx.path_graph(5)
>>> print(nx.dijkstra_path_length(G, 0, 4))
4
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None.
So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
will find the shortest red path.
The function :func:`single_source_dijkstra` computes both
path and lengthofpath if you need both, use that.
See Also

bidirectional_dijkstra(), bellman_ford_path_length()
single_source_dijkstra()
rr7Node not reachable from N)r5 _dijkstraKeyErrornxNetworkXNoPathr4r:r7r&r;er'r'r(r sB
r cCsthdS)aFind shortest weighted paths in G from a source node.
Compute shortest path between source and all other reachable
nodes for a weighted graph.
Parameters

G : NetworkX graph
source : node
Starting node for path.
cutoff : integer or float, optional
Depth to stop the search. Only return paths with length <= cutoff.
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

paths : dictionary
Dictionary of shortest path lengths keyed by target.
Raises

NodeNotFound
If `source` is not in `G`.
Examples

>>> G = nx.path_graph(5)
>>> path = nx.single_source_dijkstra_path(G, 0)
>>> path[4]
[0, 1, 2, 3, 4]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None.
So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
will find the shortest red path.
See Also

single_source_dijkstra(), single_source_bellman_ford()
cutoffr&)rr4r:rGr&r'r'r(rs>> G = nx.path_graph(5)
>>> length = nx.single_source_dijkstra_path_length(G, 0)
>>> length[4]
4
>>> for node in [0, 1, 2, 3, 4]:
... print(f"{node}: {length[node]}")
0: 0
1: 1
2: 2
3: 3
4: 4
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None.
So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
will find the shortest red path.
See Also

single_source_dijkstra(), single_source_bellman_ford_path_length()
rF)rrHr'r'r(r
,sCr
cCsthdS)aFind shortest weighted paths and lengths from a source node.
Compute the shortest path length between source and all other
reachable nodes for a weighted graph.
Uses Dijkstra's algorithm to compute shortest paths and lengths
between a source and all other reachable nodes in a weighted graph.
Parameters

G : NetworkX graph
source : node label
Starting node for path
target : node label, optional
Ending node for path
cutoff : integer or float, optional
Depth to stop the search. Only return paths with length <= cutoff.
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

distance, path : pair of dictionaries, or numeric and list.
If target is None, paths and lengths to all nodes are computed.
The return value is a tuple of two dictionaries keyed by target nodes.
The first dictionary stores distance to each target node.
The second stores the path to each target node.
If target is not None, returns a tuple (distance, path), where
distance is the distance from source to target and path is a list
representing the path from source to target.
Raises

NodeNotFound
If `source` is not in `G`.
Examples

>>> G = nx.path_graph(5)
>>> length, path = nx.single_source_dijkstra(G, 0)
>>> print(length[4])
4
>>> for node in [0, 1, 2, 3, 4]:
... print(f"{node}: {length[node]}")
0: 0
1: 1
2: 2
3: 3
4: 4
>>> path[4]
[0, 1, 2, 3, 4]
>>> length, path = nx.single_source_dijkstra(G, 0, 1)
>>> length
1
>>> path
[0, 1]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None.
So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
will find the shortest red path.
Based on the Python cookbook recipe (119466) at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466
This algorithm is not guaranteed to work if edge weights
are negative or are floating point numbers
(overflows and roundoff errors can cause problems).
See Also

single_source_dijkstra_path()
single_source_dijkstra_path_length()
single_source_bellman_ford()
)rGr7r&r)r4r:r7rGr&r'r'r(rrs^rcCstd\}}S)aFind shortest weighted paths in G from a given set of source
nodes.
Compute shortest path between any of the source nodes and all other
reachable nodes for a weighted graph.
Parameters

G : NetworkX graph
sources : nonempty set of nodes
Starting nodes for paths. If this is just a set containing a
single node, then all paths computed by this function will start
from that node. If there are two or more nodes in the set, the
computed paths may begin from any one of the start nodes.
cutoff : integer or float, optional
Depth to stop the search. Only return paths with length <= cutoff.
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

paths : dictionary
Dictionary of shortest paths keyed by target.
Examples

>>> G = nx.path_graph(5)
>>> path = nx.multi_source_dijkstra_path(G, {0, 4})
>>> path[1]
[0, 1]
>>> path[3]
[4, 3]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None.
So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
will find the shortest red path.
Raises

ValueError
If `sources` is empty.
NodeNotFound
If any of `sources` is not in `G`.
See Also

multi_source_dijkstra(), multi_source_bellman_ford()
rFrI)r4sourcesrGr&r;r<r'r'r(rsDrcCs&stdt}tdS)aFind shortest weighted path lengths in G from a given set of
source nodes.
Compute the shortest path length between any of the source nodes and
all other reachable nodes for a weighted graph.
Parameters

G : NetworkX graph
sources : nonempty set of nodes
Starting nodes for paths. If this is just a set containing a
single node, then all paths computed by this function will start
from that node. If there are two or more nodes in the set, the
computed paths may begin from any one of the start nodes.
cutoff : integer or float, optional
Depth to stop the search. Only return paths with length <= cutoff.
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

length : dict
Dict keyed by node to shortest path length to nearest source.
Examples

>>> G = nx.path_graph(5)
>>> length = nx.multi_source_dijkstra_path_length(G, {0, 4})
>>> for node in [0, 1, 2, 3, 4]:
... print(f"{node}: {length[node]}")
0: 0
1: 1
2: 2
3: 1
4: 0
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None.
So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
will find the shortest red path.
Raises

ValueError
If `sources` is empty.
NodeNotFound
If any of `sources` is not in `G`.
See Also

multi_source_dijkstra()
sources must not be empty)rG)
ValueErrorr5_dijkstra_multisource)r4rJrGr&r'r'r(rsG
rc
CsstdvrdgfSt}ddD}td}durZfSzfWSty}z tddWYd}~n
d}~00dS) aFind shortest weighted paths and lengths from a given set of
source nodes.
Uses Dijkstra's algorithm to compute the shortest paths and lengths
between one of the source nodes and the given `target`, or all other
reachable nodes if not specified, for a weighted graph.
Parameters

G : NetworkX graph
sources : nonempty set of nodes
Starting nodes for paths. If this is just a set containing a
single node, then all paths computed by this function will start
from that node. If there are two or more nodes in the set, the
computed paths may begin from any one of the start nodes.
target : node label, optional
Ending node for path
cutoff : integer or float, optional
Depth to stop the search. Only return paths with length <= cutoff.
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

distance, path : pair of dictionaries, or numeric and list
If target is None, returns a tuple of two dictionaries keyed by node.
The first dictionary stores distance from one of the source nodes.
The second stores the path from one of the sources to that node.
If target is not None, returns a tuple of (distance, path) where
distance is the distance from source to target and path is a list
representing the path from source to target.
Examples

>>> G = nx.path_graph(5)
>>> length, path = nx.multi_source_dijkstra(G, {0, 4})
>>> for node in [0, 1, 2, 3, 4]:
... print(f"{node}: {length[node]}")
0: 0
1: 1
2: 2
3: 1
4: 0
>>> path[1]
[0, 1]
>>> path[3]
[4, 3]
>>> length, path = nx.multi_source_dijkstra(G, {0, 4}, 1)
>>> length
1
>>> path
[0, 1]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None.
So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
will find the shortest red path.
Based on the Python cookbook recipe (119466) at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466
This algorithm is not guaranteed to work if edge weights
are negative or are floating point numbers
(overflows and roundoff errors can cause problems).
Raises

ValueError
If `sources` is empty.
NodeNotFound
If any of `sources` is not in `G`.
See Also

multi_source_dijkstra_path()
multi_source_dijkstra_path_length()
rKrcSsi]}gqSr'r')r#r:r'r'r(
r*z)multi_source_dijkstra..)pathsrGr7NzNo path to .)rLr5rMrArBrC)r4rJr7rGr&rOdistrEr'r'r(rjsb
rc CstgdS)aUses Dijkstra's algorithm to find shortest weighted paths from a
single source.
This is a convenience function for :func:`_dijkstra_multisource`
with all the arguments the same, except the keyword argument
`sources` set to ``[source]``.
)predrOrGr7)rM)r4r:r&rRrOrGr7r'r'r(r@s r@cCsrjnj}t}t} i}
i}t}g}
D]:}vrPtddd<
dtfq2
r 
\}}}
vrqn
<krq D]\}}}durq
}durkrq
vr6
}krt
ddn"durkrqvsNkr<
tfdurg<durg<qkrdurqqn
S)aUses Dijkstra's algorithm to find shortest weighted paths
Parameters

G : NetworkX graph
sources : nonempty iterable of nodes
Starting nodes for paths. If this is just an iterable containing
a single node, then all paths computed by this function will
start from that node. If there are two or more nodes in this
iterable, the computed paths may begin from any one of the start
nodes.
weight: function
Function with (u, v, data) input that returns that edges weight
pred: dict of lists, optional(default=None)
dict to store a list of predecessors keyed by that node
If None, predecessors are not stored.
paths: dict, optional (default=None)
dict to store the path list from source to each node, keyed by node.
If None, paths are not stored.
target : node label, optional
Ending node for path. Search is halted when target is found.
cutoff : integer or float, optional
Depth to stop the search. Only return paths with length <= cutoff.
Returns

distance : dictionary
A mapping from node to shortest distance to that node from one
of the source nodes.
Raises

NodeNotFound
If any of `sources` is not in `G`.
Notes

The optional predecessor and path dictionaries can be accessed by
the caller through the original pred and paths objects passed
as arguments. No need to explicitly return pred or paths.
Source not in GrNzContradictory paths found:znegative weights?)is_directed_succ_adjrrrrBNodeNotFoundnextitemsrLappend)r4rJr&rRrOrGr7G_succpushpoprQseencfringer:r0_r/r.rEZcostZvu_distZu_distr'r'r(rMsX3
rMcCs(t}gi}tdfS)aCompute weighted shortest path length and predecessors.
Uses Dijkstra's Method to obtain the shortest weighted paths
and return dictionaries of predecessors for each node and
distance for each node from the `source`.
Parameters

G : NetworkX graph
source : node label
Starting node for path
cutoff : integer or float, optional
Depth to stop the search. Only return paths with length <= cutoff.
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

pred, distance : dictionaries
Returns two dictionaries representing a list of predecessors
of a node and the distance to each node.
Warning: If target is specified, the dicts are incomplete as they
only contain information for the nodes along a path to target.
Raises

NodeNotFound
If `source` is not in `G`.
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The list of predecessors contains more than one element only when
there are more than one shortest paths to the key node.
Examples

>>> G = nx.path_graph(5, create_using=nx.DiGraph())
>>> pred, dist = nx.dijkstra_predecessor_and_distance(G, 0)
>>> sorted(pred.items())
[(0, []), (1, [0]), (2, [1]), (3, [2]), (4, [3])]
>>> sorted(dist.items())
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> pred, dist = nx.dijkstra_predecessor_and_distance(G, 0, 1)
>>> sorted(pred.items())
[(0, []), (1, [0])]
>>> sorted(dist.items())
[(0, 0), (1, 1)]
)rRrG)r5r@)r4r:rGr&rRr'r'r(rRsC
rccs0D]&}td\}}ffVqdS)aFind shortest weighted paths and lengths between all nodes.
Parameters

G : NetworkX graph
cutoff : integer or float, optional
Depth to stop the search. Only return paths with length <= cutoff.
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edge[u][v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Yields

(node, (distance, path)) : (node obj, (dict, dict))
Each source node has two associated dicts. The first holds distance
keyed by target and the second holds paths keyed by target.
(See single_source_dijkstra for the source/target node terminology.)
If desired you can apply `dict()` to this function to create a dict
keyed by source node to the two dicts.
Examples

>>> G = nx.path_graph(5)
>>> len_path = dict(nx.all_pairs_dijkstra(G))
>>> print(len_path[3][0][1])
2
>>> for node in [0, 1, 2, 3, 4]:
... print(f"3  {node}: {len_path[3][0][node]}")
3  0: 3
3  1: 2
3  2: 1
3  3: 0
3  4: 1
>>> len_path[3][1][1]
[3, 2, 1]
>>> for n, (dist, path) in nx.all_pairs_dijkstra(G):
... print(path[1])
[0, 1]
[1]
[2, 1]
[3, 2, 1]
[4, 3, 2, 1]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The yielded dicts only have keys for reachable nodes.
rFNr8)r4rGr&nrQr<r'r'r(rs>rccs(t}D]}dfVqdS)aCompute shortest path lengths between all nodes in a weighted graph.
Parameters

G : NetworkX graph
cutoff : integer or float, optional
Depth to stop the search. Only return paths with length <= cutoff.
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

distance : iterator
(source, dictionary) iterator with dictionary keyed by target and
shortest path length as the key value.
Examples

>>> G = nx.path_graph(5)
>>> length = dict(nx.all_pairs_dijkstra_path_length(G))
>>> for node in [0, 1, 2, 3, 4]:
... print(f"1  {node}: {length[1][node]}")
1  0: 1
1  1: 0
1  2: 1
1  3: 2
1  4: 3
>>> length[3][2]
1
>>> length[2][2]
0
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The dictionary returned only has keys for reachable node pairs.
rFN)r
)r4rGr&r;rcr'r'r(rs4rccs(t}D]}dfVqdS)a@Compute shortest paths between all nodes in a weighted graph.
Parameters

G : NetworkX graph
cutoff : integer or float, optional
Depth to stop the search. Only return paths with length <= cutoff.
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

distance : dictionary
Dictionary, keyed by source and target, of shortest paths.
Examples

>>> G = nx.path_graph(5)
>>> path = dict(nx.all_pairs_dijkstra_path(G))
>>> print(path[0][4])
[0, 1, 2, 3, 4]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
See Also

floyd_warshall(), all_pairs_bellman_ford_path()
rFN)r)r4rGr&r<rcr'r'r(rsrFc svrtddttfddtjddDrNtddi}gi}td krrfSttgd
}fS)a>Compute shortest path lengths and predecessors on shortest paths
in weighted graphs.
The algorithm has a running time of $O(mn)$ where $n$ is the number of
nodes and $m$ is the number of edges. It is slower than Dijkstra but
can handle negative edge weights.
Parameters

G : NetworkX graph
The algorithm works for all types of graphs, including directed
graphs and multigraphs.
source: node label
Starting node for path
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
heuristic : bool
Determines whether to use a heuristic to early detect negative
cycles at a hopefully negligible cost.
Returns

pred, dist : dictionaries
Returns two dictionaries keyed by node to predecessor in the
path and to the distance from the source respectively.
Raises

NodeNotFound
If `source` is not in `G`.
NetworkXUnbounded
If the (di)graph contains a negative cost (di)cycle, the
algorithm raises an exception to indicate the presence of the
negative cost (di)cycle. Note: any negative weight edge in an
undirected graph is a negative cost cycle.
Examples

>>> G = nx.path_graph(5, create_using=nx.DiGraph())
>>> pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0)
>>> sorted(pred.items())
[(0, []), (1, [0]), (2, [1]), (3, [2]), (4, [3])]
>>> sorted(dist.items())
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0, 1)
>>> sorted(pred.items())
[(0, []), (1, [0]), (2, [1]), (3, [2]), (4, [3])]
>>> sorted(dist.items())
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> G = nx.cycle_graph(5, create_using=nx.DiGraph())
>>> G[1][2]["weight"] = 7
>>> nx.bellman_ford_predecessor_and_distance(G, 0)
Traceback (most recent call last):
...
networkx.exception.NetworkXUnbounded: Negative cost cycle detected.
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The dictionaries returned only have keys for nodes reachable from
the source.
In the case where the (di)graph is not connected, if a component
not containing the source contains a negative cost (di)cycle, it
will not be detected.
In NetworkX v2.1 and prior, the source node had predecessor `[None]`.
In NetworkX v2.2 this changed to the source node having predecessor `[]`
r> is not found in the graphc3s$]\}}}dkVqdSrNr'r#r.r/r0r%r'r(r)r*z8bellman_ford_predecessor_and_distance..Tr2Negative cost cycle detected.rr )rRrQr7 heuristic)rBrXr5anyselfloop_edgesNetworkXUnboundedlen
_bellman_ford)r4r:r7r&rirQrRr'r%r(rIsZ
rTcsPD]}vrtddqdur:ddD}durPddD}dddD} fd dD}
rjnj}td
}t}
i}t}tr }
tfddDr}D]
\}}}
krrn
vr.cSsi]
}dqSrr'ror'r'r(rNr*)NNcSsi]
}dqSNr'ror'r'r(rNr*csi]
}qSr'r'ro)nonexistent_edger'r(rNr*infc3s]}vVqdSrqr')r#Zpred_u)in_qr'r(r)
r*z _bellman_ford..rhrr )rBrXrUsuccadjfloatrmrsetpopleftremoveallrZr"rlr[addrrY)r4r:r&rRrOrQr7risZ pred_edgeZ
recent_updater\rsrcrqr.Zdist_ur/rEZdist_vZcount_vrJZdstsdstgenr')rtrrr(rnsb;
rncCstd\}}S)adReturns the shortest path from source to target in a weighted graph G.
Parameters

G : NetworkX graph
source : node
Starting node
target : node
Ending node
weight: string, optional (default='weight')
Edge data key corresponding to the edge weight
Returns

path : list
List of nodes in a shortest path.
Raises

NodeNotFound
If `source` is not in `G`.
NetworkXNoPath
If no path exists between source and target.
Examples

>>> G = nx.path_graph(5)
>>> print(nx.bellman_ford_path(G, 0, 4))
[0, 1, 2, 3, 4]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
See Also

dijkstra_path(), bellman_ford_path_length()
r6rr9r'r'r(r=s,rc
CstkrdSt}tgd}z
WStyn}z$tddWYd}~n
d}~00dS)a~Returns the shortest path length from source to target
in a weighted graph.
Parameters

G : NetworkX graph
source : node label
starting node for path
target : node label
ending node for path
weight: string, optional (default='weight')
Edge data key corresponding to the edge weight
Returns

length : number
Shortest path length.
Raises

NodeNotFound
If `source` is not in `G`.
NetworkXNoPath
If no path exists between source and target.
Examples

>>> G = nx.path_graph(5)
>>> print(nx.bellman_ford_path_length(G, 0, 4))
4
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
See Also

dijkstra_path_length(), bellman_ford_path()
rr=znode r?Nr5rnrArBrCrDr'r'r(rms
rcCstd\}}S)aWCompute shortest path between source and all other reachable
nodes for a weighted graph.
Parameters

G : NetworkX graph
source : node
Starting node for path.
weight: string, optional (default='weight')
Edge data key corresponding to the edge weight
Returns

paths : dictionary
Dictionary of shortest path lengths keyed by target.
Raises

NodeNotFound
If `source` is not in `G`.
Examples

>>> G = nx.path_graph(5)
>>> path = nx.single_source_bellman_ford_path(G, 0)
>>> path[4]
[0, 1, 2, 3, 4]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
See Also

single_source_dijkstra(), single_source_bellman_ford()
r%r)r4r:r&r;r<r'r'r(rs)rcCst}tgS)aCompute the shortest path length between source and all other
reachable nodes for a weighted graph.
Parameters

G : NetworkX graph
source : node label
Starting node for path
weight: string, optional (default='weight')
Edge data key corresponding to the edge weight.
Returns

length : iterator
(target, shortest path length) iterator
Raises

NodeNotFound
If `source` is not in `G`.
Examples

>>> G = nx.path_graph(5)
>>> length = dict(nx.single_source_bellman_ford_path_length(G, 0))
>>> length[4]
4
>>> for node in [0, 1, 2, 3, 4]:
... print(f"{node}: {length[node]}")
0: 0
1: 1
2: 2
3: 3
4: 4
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
See Also

single_source_dijkstra(), single_source_bellman_ford()
)r5rn)r4r:r&r'r'r(rs0
rc
CskrdgfSt}gi}tgd}durJfSzfWSty}z(dd}tWYd}~n
d}~00dS)aCompute shortest paths and lengths in a weighted graph G.
Uses BellmanFord algorithm for shortest paths.
Parameters

G : NetworkX graph
source : node label
Starting node for path
target : node label, optional
Ending node for path
Returns

distance, path : pair of dictionaries, or numeric and list
If target is None, returns a tuple of two dictionaries keyed by node.
The first dictionary stores distance from one of the source nodes.
The second stores the path from one of the sources to that node.
If target is not None, returns a tuple of (distance, path) where
distance is the distance from source to target and path is a list
representing the path from source to target.
Raises

NodeNotFound
If `source` is not in `G`.
Examples

>>> G = nx.path_graph(5)
>>> length, path = nx.single_source_bellman_ford(G, 0)
>>> print(length[4])
4
>>> for node in [0, 1, 2, 3, 4]:
... print(f"{node}: {length[node]}")
0: 0
1: 1
2: 2
3: 3
4: 4
>>> path[4]
[0, 1, 2, 3, 4]
>>> length, path = nx.single_source_bellman_ford(G, 0, 1)
>>> length
1
>>> path
[0, 1]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
See Also

single_source_dijkstra()
single_source_bellman_ford_path()
single_source_bellman_ford_path_length()
r)rOr7Nr>r?r)r4r:r7r&rOrQrEmsgr'r'r(rs>
rccs*t}D]}tdfVqdS)a Compute shortest path lengths between all nodes in a weighted graph.
Parameters

G : NetworkX graph
weight: string, optional (default='weight')
Edge data key corresponding to the edge weight
Returns

distance : iterator
(source, dictionary) iterator with dictionary keyed by target and
shortest path length as the key value.
Examples

>>> G = nx.path_graph(5)
>>> length = dict(nx.all_pairs_bellman_ford_path_length(G))
>>> for node in [0, 1, 2, 3, 4]:
... print(f"1  {node}: {length[1][node]}")
1  0: 1
1  1: 0
1  2: 1
1  3: 2
1  4: 3
>>> length[3][2]
1
>>> length[2][2]
0
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The dictionary returned only has keys for reachable node pairs.
r%N)rdict)r4r&r;rcr'r'r(rVs'rccs&t}D]}dfVqdS)a Compute shortest paths between all nodes in a weighted graph.
Parameters

G : NetworkX graph
weight: string, optional (default='weight')
Edge data key corresponding to the edge weight
Returns

distance : dictionary
Dictionary, keyed by source and target, of shortest paths.
Examples

>>> G = nx.path_graph(5)
>>> path = dict(nx.all_pairs_bellman_ford_path(G))
>>> print(path[0][4])
[0, 1, 2, 3, 4]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
See Also

floyd_warshall(), all_pairs_dijkstra_path()
r%N)r)r4r&r<rcr'r'r(rs rcsvrtddttfddtjddDrNtdtdkrjd id
ifSrzjnj t
dfdd
Dd
<d ifdd}fdd}h}r}}qԇfdd
DfS)a
Compute shortest path lengths and predecessors on shortest paths
in weighted graphs.
The algorithm has a running time of $O(mn)$ where $n$ is the number of
nodes and $m$ is the number of edges. It is slower than Dijkstra but
can handle negative edge weights.
Parameters

G : NetworkX graph
The algorithm works for all types of graphs, including directed
graphs and multigraphs.
source: node label
Starting node for path
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

pred, dist : dictionaries
Returns two dictionaries keyed by node to predecessor in the
path and to the distance from the source respectively.
Raises

NodeNotFound
If `source` is not in `G`.
NetworkXUnbounded
If the (di)graph contains a negative cost (di)cycle, the
algorithm raises an exception to indicate the presence of the
negative cost (di)cycle. Note: any negative weight edge in an
undirected graph is a negative cost cycle.
Examples

>>> G = nx.path_graph(5, create_using=nx.DiGraph())
>>> pred, dist = nx.goldberg_radzik(G, 0)
>>> sorted(pred.items())
[(0, None), (1, 0), (2, 1), (3, 2), (4, 3)]
>>> sorted(dist.items())
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> G = nx.cycle_graph(5, create_using=nx.DiGraph())
>>> G[1][2]["weight"] = 7
>>> nx.goldberg_radzik(G, 0)
Traceback (most recent call last):
...
networkx.exception.NetworkXUnbounded: Negative cost cycle detected.
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The dictionaries returned only have keys for nodes reachable from
the source.
In the case where the (di)graph is not connected, if a component
not containing the source contains a negative cost (di)cycle, it
will not be detected.
r>rdc3s$]\}}}dkVqdSrer'rfr%r'r(r)r*z"goldberg_radzik..Trgrhr Nrrscsi]
}qSr'r'r#r.)rsr'r(rNr*z#goldberg_radzik..c sg}i}D]`vrqtfddDrJqtfg}h}d<rd\}zt\}}Wn2tyYqnYn0}}  krn k}
<<vrBt
<tf qnvrnt
krnt
dqnqS)zeTopologically sort nodes relabeled in the previous round and detect
negative cycles.
c3s*]"\}}kVqdSrqr')r#r/rE)r0d_ur.r&r'r(r)r*z5goldberg_radzik..topo_sort..rrh)
r{rZiterrY
StopIterationr[r^rzintrrBrlreverse) relabeledto_scanZ neg_countstackZin_stackitr/rEtZd_vZis_negr\r0rRr&)rr.r( topo_sortsD
$
z"goldberg_radzik..topo_sortcslt}D]\}}D]B\}}}kr"<<q"q
S)z,Relax outedges of relabeled nodes.
)rxrZr)rrr.rr/rEZw_err'r(relax?szgoldberg_radzik..relaxcsi]}qSr'r'r)r0r'r(rNWr*)rBrXr5rjrkrlrmrUrurvrw)r4r:r&rrrrr')r\r0rsrRr&r(rs,L
8
rc svtfddDzFztdWn"tjyVYWdS0Wn0dS)aReturns True if there exists a negative edge cycle anywhere in G.
Parameters

G : NetworkX graph
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
heuristic : bool
Determines whether to use a heuristic to early detect negative
cycles at a negligible cost. In case of graphs with a negative cycle,
the performance of detection increases by at least an order of magnitude.
Returns

negative_cycle : bool
True if a negative edge cycle exists, otherwise False.
Examples

>>> G = nx.cycle_graph(5, create_using=nx.DiGraph())
>>> print(nx.negative_edge_cycle(G))
False
>>> G[1][2]["weight"] = 7
>>> print(nx.negative_edge_cycle(G))
True
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
This algorithm uses bellman_ford_predecessor_and_distance() but finds
negative cycles on any component by first adding a new node connected to
every node, and starting bellman_ford_predecessor_and_distance on that
node. It then removes that extra node.
csg]}fqSr'r')r#rcZnewnoder'r(
r*z'negative_edge_cycle..)riTF)rZadd_edges_fromrrBrlremove_node)r4r&rir'rr(r[s1
rcCsvsvr,ddd}tkr>dgfSt}t}t}iig}gigig}ggg} didig}
t} ddtf ddtfrjj g}nj
j
g}g}
d} dr drd} \}}}vr"q<dvrH
fSD]N\}}dkr}n}vrkrtdn
vs
krX
< tfg<
dvrX
dvrX
d
d}
gksnkrX}ddd}
ddd}
qXqtdd d
dS)aDijkstra's algorithm for shortest paths using bidirectional search.
Parameters

G : NetworkX graph
source : node
Starting node.
target : node
Ending node.
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

length, path : number and list
length is the distance from source to target.
path is a list of nodes on a path from source to target.
Raises

NodeNotFound
If either `source` or `target` is not in `G`.
NetworkXNoPath
If no path exists between source and target.
Examples

>>> G = nx.path_graph(5)
>>> length, path = nx.bidirectional_dijkstra(G, 0, 4)
>>> print(length)
4
>>> print(path)
[0, 1, 2, 3, 4]
Notes

Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
In practice bidirectional Dijkstra is much more than twice as fast as
ordinary Dijkstra.
Ordinary Dijkstra expands nodes in a spherelike manner from the
source. The radius of this sphere will eventually be the length
of the shortest path. Bidirectional Dijkstra will expand nodes
from both the source and the target, making two spheres of half
this radius. Volume of the first sphere is `\pi*r*r` while the
others are `2*\pi*r/2*r/2`, making up half the volume.
This algorithm is not guaranteed to work if edge weights
are negative or are floating point numbers
(overflows and roundoff errors can cause problems).
See Also

shortest_path
shortest_path_length
zEither source z or target z is not in Grr z,Contradictory paths found: negative weights?NzNo path between z and rP)rBrXr5rrrrYrUrVZ_predrWrZrLrrC)r4r:r7r&rr]r^distsrOrar_r`ZneighsZ finalpathdirrQrbr/Z finaldistwr0ZvwLengthZ totaldistZrevpathr'r'r(r
s^I
r
cstjdstdddD}ddD}tttdfddfd d
fddDS)uUses Johnson's Algorithm to compute shortest paths.
Johnson's Algorithm finds a shortest path between each pair of
nodes in a weighted graph even if negative weights are present.
Parameters

G : NetworkX graph
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this 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.
Returns

distance : dictionary
Dictionary, keyed by source and target, of shortest paths.
Raises

NetworkXError
If given graph is not weighted.
Examples

>>> graph = nx.DiGraph()
>>> graph.add_weighted_edges_from(
... [("0", "3", 3), ("0", "1", 5), ("0", "2", 2), ("1", "2", 4), ("2", "3", 1)]
... )
>>> paths = nx.johnson(graph, weight="weight")
>>> paths["0"]["2"]
['0', '1', '2']
Notes

Johnson's algorithm is suitable even for graphs with negative weights. It
works by using the Bellman–Ford algorithm to compute a transformation of
the input graph that removes all negative weights, allowing Dijkstra's
algorithm to be used on the transformed graph.
The time complexity of this algorithm is $O(n^2 \log n + n m)$,
where $n$ is the number of nodes and $m$ the number of edges in the
graph. For dense graphs, this may be faster than the Floyd–Warshall
algorithm.
See Also

floyd_warshall_predecessor_and_distance
floyd_warshall_numpy
all_pairs_shortest_path
all_pairs_shortest_path_length
all_pairs_dijkstra_path
bellman_ford_predecessor_and_distance
all_pairs_bellman_ford_path
all_pairs_bellman_ford_path_length
r%zGraph is not weighted.cSsi]
}dqSrpr'ror'r'r(rNlr*zjohnson..cSsi]
}gqSr'r'ror'r'r(rNmr*)rRrQcsSrqr'r)dist_bellmanr&r'r(
new_weightuszjohnson..new_weightcsgi}tdS)N)rO)r@)r/rO)r4rr'r( dist_pathxs
zjohnson..dist_pathcsi]}qSr'r'ro)rr'r(rN}r*)rBZis_weightedZ
NetworkXErrorr5rnlist)r4r&rQrRr')r4rrrr&r(r&sC
r)r&)r&)Nr&)Nr&)NNr&)Nr&)Nr&)NNr&)NNNN)NNNN)Nr&)Nr&)Nr&)Nr&)Nr&F)NNNNT)r&)r&)r&)r&)Nr&)r&)r&)r&)r&T)r&)r&)+__doc__collectionsrheapqrr itertoolsrZnetworkxrBZnetworkx.utilsrZ*networkx.algorithms.shortest_paths.genericr__all__r5rr rr
rrrrr@rMrrrrrrnrrrrrrrrrr
rr'r'r'r(sR(
P
L
?
F
c
H
M
s
g
H
C
9
4
o
0
:

4
N
,
&
4
=