
    VhA                       d Z ddlmZ ddlmZmZ ddlmZ ddlZ	ddl
mZ g dZd Z e	j                  d	
      d(d       Z e	j                  d	
      d(d       Z e	j                  d	
      d)d       Z e	j                  d	
      d)d       Z e	j                  d	
      d*d       Z e	j                  d	
      d)d       Z e	j                  d	
      d)d       Z e	j                  d	
      d*d       Zd+dZ	 d+dZ e	j                  d	
      d)d       Z e	j                  d	
      d)d       Z e	j                  d	
      d)d       Z e	j                  d	
      d)d       Z e	j                  d	
      	 d,d       Z	 	 	 	 	 d-dZ	 	 d.dZ e	j                  d	
      d(d       Z  e	j                  d	
      d(d       Z! e	j                  d	
      d(d       Z" e	j                  d	
      d(d       Z# e	j                  d	
      d)d        Z$ e	j                  d	
      d(d!       Z% e	j                  d	
      d(d"       Z& e	j                  d	
      d(d#       Z' e	j                  d	
      d/d$       Z( e	j                  d	
      d(d%       Z) e	j                  d	
      d(d&       Z* e	j                  d	
      d(d'       Z+y)0z/
Shortest path algorithms for weighted graphs.
    )deque)heappopheappush)countN)_build_paths_from_predecessors)dijkstra_pathdijkstra_path_lengthbidirectional_dijkstrasingle_source_dijkstrasingle_source_dijkstra_path"single_source_dijkstra_path_lengthmulti_source_dijkstramulti_source_dijkstra_path!multi_source_dijkstra_path_lengthall_pairs_dijkstraall_pairs_dijkstra_pathall_pairs_dijkstra_path_length!dijkstra_predecessor_and_distancebellman_ford_pathbellman_ford_path_lengthsingle_source_bellman_fordsingle_source_bellman_ford_path&single_source_bellman_ford_path_lengthall_pairs_bellman_ford_path"all_pairs_bellman_ford_path_length%bellman_ford_predecessor_and_distancenegative_edge_cyclefind_negative_cyclegoldberg_radzikjohnsonc                 R    t              rS | j                         rfdS fdS )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.

    c                 H    t        fd|j                         D              S )Nc              3   B   K   | ]  }|j                  d         yw)   Nget).0attrweights     [/home/dcms/DCMS/lib/python3.12/site-packages/networkx/algorithms/shortest_paths/weighted.py	<genexpr>z5_weight_function.<locals>.<lambda>.<locals>.<genexpr>M   s     "N4488FA#6"Ns   )minvalues)uvdr)   s      r*   <lambda>z"_weight_function.<locals>.<lambda>M   s    s"N188:"NN     c                 (    |j                  d      S )Nr$   r%   )r.   r/   datar)   s      r*   r1   z"_weight_function.<locals>.<lambda>N   s    dhhvq1 r2   )callableis_multigraph)Gr)   s    `r*   _weight_functionr8   )   s*    <  	NN11r2   r)   )
edge_attrsc                 *    t        | |||      \  }}|S )a}
  Returns 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 or None to indicate a hidden edge.

    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]

    Find edges of shortest path in Multigraph

    >>> G = nx.MultiDiGraph()
    >>> G.add_weighted_edges_from([(1, 2, 0.75), (1, 2, 0.5), (2, 3, 0.5), (1, 3, 1.5)])
    >>> nodes = nx.dijkstra_path(G, 1, 3)
    >>> edges = nx.utils.pairwise(nodes)
    >>> list(
    ...     (u, v, min(G[u][v], key=lambda k: G[u][v][k].get("weight", 1)))
    ...     for u, v in edges
    ... )
    [(1, 2, 1), (2, 3, 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.

    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 length-of-path if you need both, use that.

    See Also
    --------
    bidirectional_dijkstra
    bellman_ford_path
    single_source_dijkstra
    targetr)   r   r7   sourcer<   r)   lengthpaths         r*   r   r   Q   s    t ,AvfVTNVTKr2   c                     || vrt        j                  d| d      ||k(  ryt        | |      }t        | |||      }	 ||   S # t        $ r!}t        j
                  d| d|       |d}~ww xY w)aX  Returns 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 or None to indicate a hidden edge.

    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)
    >>> 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 length-of-path if you need both, use that.

    See Also
    --------
    bidirectional_dijkstra
    bellman_ford_path_length
    single_source_dijkstra

    Node  not found in graphr   r<    not reachable from N)nxNodeNotFoundr8   	_dijkstraKeyErrorNetworkXNoPathr7   r?   r<   r)   r@   errs         r*   r	   r	      s    H QoofX-@ABBa(Fq&&8FWf~ W%x/CF8 LMSVVWs    A 	A/A**A/c                 "    t        | |h||      S )a0  Find 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
        Length (sum of edge weights) at which the search is stopped.
        If cutoff is provided, only return paths with summed weight <= 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 or None to indicate a hidden edge.

    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)   )r   r7   r?   rP   r)   s       r*   r   r      s    | &a&&PPr2   c                 "    t        | |h||      S )a  Find shortest weighted path lengths in G from a source node.

    Compute 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

    cutoff : integer or float, optional
        Length (sum of edge weights) at which the search is stopped.
        If cutoff is provided, only return paths with summed weight <= 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 or None to indicate a hidden edge.

    Returns
    -------
    length : dict
        Dict keyed by node to shortest path length from source.

    Raises
    ------
    NodeNotFound
        If `source` is not in `G`.

    Examples
    --------
    >>> 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

    rO   )r   rQ   s       r*   r   r   @  s    J -QPVWWr2   c                 $    t        | |h|||      S )a  Find 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
        Length (sum of edge weights) at which the search is stopped.
        If cutoff is provided, only return paths with summed weight <= 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 or None to indicate a hidden edge.

    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)
    >>> 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
    https://code.activestate.com/recipes/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
    )rP   r<   r)   r   )r7   r?   r<   rP   r)   s        r*   r   r     s    B !	F8F6& r2   c                 *    t        | |||      \  }}|S )a  Find 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 : non-empty 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
        Length (sum of edge weights) at which the search is stopped.
        If cutoff is provided, only return paths with summed weight <= 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 or None to indicate a hidden edge.

    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

    rO   rT   )r7   sourcesrP   r)   r@   rA   s         r*   r   r     s    L )GF6RLFDKr2   c                     |st        d      |D ]  }|| vst        j                  d| d       t        | |      }t	        | |||      S )a  Find 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 : non-empty 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
        Length (sum of edge weights) at which the search is stopped.
        If cutoff is provided, only return paths with summed weight <= 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 or None to indicate a hidden edge.

    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 emptyrC   rD   )rP   )
ValueErrorrG   rH   r8   _dijkstra_multisource)r7   rV   rP   r)   ss        r*   r   r   8  sd    R 455 BA://E!,?"@AAB a(F GVFCCr2   c                 T   |st        d      |D ]  }|| vst        j                  d| d       ||v rd|gfS t        | |      }|D ci c]  }||g }}t	        | |||||      }|||fS 	 ||   ||   fS c c}w # t
        $ r}	t        j                  d| d      |	d}	~	ww xY w)	a  Find 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 : non-empty 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
        Length (sum of edge weights) at which the search is stopped.
        If cutoff is provided, only return paths with summed weight <= 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 or None to indicate a hidden edge.

    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
    https://code.activestate.com/recipes/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

    rX   rC   rD   r   )pathsrP   r<   NzNo path to .)rY   rG   rH   r8   rZ   rJ   rK   )
r7   rV   r<   rP   r)   r[   r?   r]   distrM   s
             r*   r   r     s    H 455 BA://E!,?"@AAB F8}a(F,34&VfX4E4 	7F%vD ~e}BVeFm,, 5  B+fXQ 78cABs   A:0	A? ?	B'B""B'c           	      (    t        | |g|||||      S )a  Uses 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]``.

    )predr]   rP   r<   )rZ   )r7   r?   r)   ra   r]   rP   r<   s          r*   rI   rI     s"     !	F8V$eF6 r2   c                 t   | j                   }i }i }	t               }
g }|D ]  }d|	|<   t        |dt        |
      |f       ! |rt	        |      \  }}}||v r|||<   ||k(  r	 |S ||   j                         D ]  \  }} ||||      }|||   |z   }|||kD  r#||v r4||   }||k  rt        dd      |@||k(  sF||   j                  |       [||	vs||	|   k  r5||	|<   t        ||t        |
      |f       |||   |gz   ||<   ||g||<   ||	|   k(  s|||   j                  |        |r|S )a{  Uses Dijkstra's algorithm to find shortest weighted paths

    Parameters
    ----------
    G : NetworkX graph

    sources : non-empty 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 edge's weight
        or None to indicate a hidden edge

    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
        Length (sum of edge weights) at which the search is stopped.
        If cutoff is provided, only return paths with summed weight <= 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.

    r   zContradictory paths found:znegative weights?)_adjr   r   nextr   itemsrY   append)r7   rV   r)   ra   r]   rP   r<   G_succr_   seencfringer?   r0   _r/   r.   ecostvu_distu_dists                        r*   rZ   rZ     s   j VVFDD 	AF /V!T!Wf-./ FO	Aq9Q;8 K7 1IOO% 	&DAq!Q?D|1gnG!V#DyaV#$%ACVWW%'V*;GNN1%$'DG"3!Q'47A!67$$Qx1#~E!H# cDGDG##GNN1%/	& D Kr2   c                     || vrt        j                  d| d      t        | |      }|g i}|t        | ||||      fS )a  Compute 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
        Length (sum of edge weights) at which the search is stopped.
        If cutoff is provided, only return paths with summed weight <= 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 or None to indicate a hidden edge.

    Returns
    -------
    pred, distance : dictionaries
        Returns two dictionaries representing a list of predecessors
        of a node and the distance to each node.

    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)]
    rC    is not found in the graph)ra   rP   )rG   rH   r8   rI   )r7   r?   rP   r)   ra   s        r*   r   r   u  sR    D QoofX-GHIIa(FB<D)AvvDHIIr2   c              #   N   K   | D ]  }t        | |||      \  }}|||ff  yw)a  Find shortest weighted paths and lengths between all nodes.

    Parameters
    ----------
    G : NetworkX graph

    cutoff : integer or float, optional
        Length (sum of edge weights) at which the search is stopped.
        If cutoff is provided, only return paths with summed weight <= 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 or None to indicate a hidden edge.

    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))
    >>> 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.
    rO   Nr=   )r7   rP   r)   nr_   rA   s         r*   r   r     s;     @   +AqO
d4, s   #%c              #   F   K   t         }| D ]  }| || |||      f  yw)a  Compute shortest path lengths between all nodes in a weighted graph.

    Parameters
    ----------
    G : NetworkX graph

    cutoff : integer or float, optional
        Length (sum of edge weights) at which the search is stopped.
        If cutoff is provided, only return paths with summed weight <= 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 or None to indicate a hidden edge.

    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.
    rO   N)r   )r7   rP   r)   r@   rs   s        r*   r   r     s3     l 0F >&AfV<==>   !c              #   F   K   t         }| D ]  }| || |||      f  yw)a  Compute shortest paths between all nodes in a weighted graph.

    Parameters
    ----------
    G : NetworkX graph

    cutoff : integer or float, optional
        Length (sum of edge weights) at which the search is stopped.
        If cutoff is provided, only return paths with summed weight <= 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 or None to indicate a hidden edge.

    Returns
    -------
    paths : iterator
        (source, dictionary) iterator with dictionary keyed by target and
        shortest path as the key value.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> path = dict(nx.all_pairs_dijkstra_path(G))
    >>> 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

    rO   N)r   )r7   rP   r)   rA   rs   s        r*   r   r   >  s3     ` 'D <$q!F6:;;<ru   c           	         || vrt        j                  d| d      t        |       | j                         r?t	        fdt        j
                  | dd      D              rSt        j                  d      t	        fdt        j
                  | d      D              rt        j                  d      |d	i}|g i}t        |       d
k(  r||fS t        |       t        | |g||||      }||fS )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.

    If a negative cycle is detected, you can use :func:`find_negative_cycle`
    to return the cycle and examine it. Shortest paths are not defined when
    a negative cycle exists because once reached, the path can cycle forever
    to build up arbitrarily low 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

    target : node label, optional
        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.

    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 (di)cycle, the
        algorithm raises an exception to indicate the presence of the
        negative (di)cycle.  Note: any negative weight edge in an
        undirected graph is a negative 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 cycle detected.

    See Also
    --------
    find_negative_cycle

    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 (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 `[]`
    rC   rq   c              3   F   K   | ]  \  }}}} ||||i      d k    ywr   N r'   r.   r/   kr0   r)   s        r*   r+   z8bellman_ford_predecessor_and_distance.<locals>.<genexpr>  3      
1a 1a!Q 1$
   !Tkeysr4   Negative cycle detected.c              3   @   K   | ]  \  }}} |||      d k    ywry   rz   r'   r.   r/   r0   r)   s       r*   r+   z8bellman_ford_predecessor_and_distance.<locals>.<genexpr>  $     Rwq!QvaA"R   r4   r   r$   )ra   r_   r<   	heuristic)	rG   rH   r8   r6   anyselfloop_edgesNetworkXUnboundedlen_bellman_ford)r7   r?   r<   r)   r   r_   ra   s      `   r*   r   r   t  s    N QoofX-GHIIa(F 
 //4H
 
 &&'ABBR"2C2CAD2QRR&&'ABBA;DB<D
1v{Tza(F	F8V$T&ID $<r2   c                    ||D ci c]  }|g  }}|t         j                  |d      }t        | |||||      }	|	t        j                  d      |4t        |      }
||gn|}|D ]  }t        |
||      }t        |      ||<    |S c c}w )u  Calls relaxation loop for Bellman–Ford algorithm and builds paths

    This is an implementation of the SPFA variant.
    See https://en.wikipedia.org/wiki/Shortest_Path_Faster_Algorithm

    Parameters
    ----------
    G : NetworkX graph

    source: list
        List of source nodes. The shortest path from any of the source
        nodes will be found if multiple sources are provided.

    weight : 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.

    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

    dist: dict, optional (default=None)
        dict to store distance from source to the keyed node
        If None, returned dist dict contents default to 0 for every node in the
        source list

    target: node label, optional
        Ending node for path. Path lengths to other destinations may (and
        probably will) be incorrect.

    heuristic : bool
        Determines whether to use a heuristic to early detect negative
        cycles at a hopefully negligible cost.

    Returns
    -------
    dist : dict
        Returns a dict keyed by node to the distance from the source.
        Dicts for paths and pred are in the mutated input dicts by those names.

    Raises
    ------
    NodeNotFound
        If any of `source` is not in `G`.

    NetworkXUnbounded
        If the (di)graph contains a negative (di)cycle, the
        algorithm raises an exception to indicate the presence of the
        negative (di)cycle.  Note: any negative weight edge in an
        undirected graph is a negative cycle
    r   r   )dictfromkeys_inner_bellman_fordrG   r   setr   rd   )r7   r?   r)   ra   r]   r_   r<   r   r/   negative_cycle_foundrV   dstsdstgens                 r*   r   r     s    F |%&!2&&|}}VQ'.	 '""#=>>f+!-x4 	#C0#tDCcE#J	# K/ 's   
B
c                 $   |D ]  }|| vst        j                  d| d       ||D ci c]  }|g  }}|t        j                  |d      }d}t        j                  |      }	t        j                  ||      }
| j                  }t        d      }t        |       }i }t        |      }t        |      |rR|j                         }j                  |       t        fd||   D              r||   }||   j                         D ]  \  }}| ||||      z   }||j                  ||      k  r|r;||
|   v r||   j                  |       |c S ||	v r|	|   |k(  r	|
|   |
|<   n||f|
|<   |vrF|j                  |       j                  |        |j                  |d      dz   }||k(  r|c S |||<   |||<   |g||<   ||	|<   |j                  |      ||j                  |      k(  s||   j                  |        |rRyc c}w )	uH  Inner Relaxation loop for Bellman–Ford algorithm.

    This is an implementation of the SPFA variant.
    See https://en.wikipedia.org/wiki/Shortest_Path_Faster_Algorithm

    Parameters
    ----------
    G : NetworkX graph

    source: list
        List of source nodes. The shortest path from any of the source
        nodes will be found if multiple sources are provided.

    weight : 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.

    pred: dict of lists
        dict to store a list of predecessors keyed by that node

    dist: dict, optional (default=None)
        dict to store distance from source to the keyed node
        If None, returned dist dict contents default to 0 for every node in the
        source list

    heuristic : bool
        Determines whether to use a heuristic to early detect negative
        cycles at a hopefully negligible cost.

    Returns
    -------
    node or None
        Return a node `v` where processing discovered a negative cycle.
        If no negative cycle found, return None.

    Raises
    ------
    NodeNotFound
        If any of `source` is not in `G`.
    Source z	 not in GNr   )NNinfc              3   &   K   | ]  }|v 
 y wNrz   )r'   pred_uin_qs     r*   r+   z&_inner_bellman_ford.<locals>.<genexpr>  s     8fvT!8s   r$   )rG   rH   r   r   rc   floatr   r   r   popleftremoveallre   r&   rf   add)r7   rV   r)   ra   r_   r   r[   r/   nonexistent_edge	pred_edgerecent_updaterg   r   rs   r   qr.   dist_url   dist_vcount_vr   s                        @r*   r   r   T  s5   d  :A://GA3i"899: |&'!2''|}}Wa( $g&IMM'+;<MVVF
,CAAEgAw<D
IIKA 8Q88!WFq	) '&1&Aq/1DHHQ,, !a 00 GNN1-#$H 	>ila.?/<Q/?M!,011vM!,}"+%))Aq/A"5"a<#$H#*a$DG cDG#$IaLXXa[,488A;1FGNN1%O'& b E (s   
Hc                 *    t        | |||      \  }}|S )a  Returns 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 or function (default="weight")
        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)
    >>> 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
    r;   r   r>   s         r*   r   r     s    n .avVLFDKr2   c                     ||k(  r|| vrt        j                  d| d      yt        | |      }t        | |g||      }	 ||   S # t        $ r!}t        j
                  d| d|       |d}~ww xY w)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 or function (default="weight")
        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)
    >>> 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
    rC   rD   r   rE   znode rF   NrG   rH   r8   r   rJ   rK   rL   s         r*   r   r     s    p ?//E&1D"EFFa(F1vhv>FWf~ W%x/CF8 LMSVVWs   A 	A0A++A0c                 (    t        | ||      \  }}|S )a}  Compute 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 or function (default="weight")
        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_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   )r7   r?   r)   r@   rA   s        r*   r   r   R  s    h 06&INVTKr2   c                 6    t        | |      }t        | |g|      S )a  Compute 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 or function (default="weight")
        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 : dictionary
        Dictionary of shortest path length keyed by target

    Raises
    ------
    NodeNotFound
        If `source` is not in `G`.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> length = 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

    )r8   r   )r7   r?   r)   s      r*   r   r     s"    v a(FVHf--r2   c                    ||k(  r"|| vrt        j                  d| d      d|gfS t        | |      }||gi}t        | |g|||      }|||fS 	 ||   ||   fS # t        $ r#}d| d| }t        j
                  |      |d}~ww xY w)a  Compute shortest paths and lengths in a weighted graph G.

    Uses Bellman-Ford algorithm for shortest paths.

    Parameters
    ----------
    G : NetworkX graph

    source : node label
        Starting node for path

    target : node label, optional
        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
    -------
    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)
    >>> 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
    rC   rq   r   )r]   r<   NrF   r   )r7   r?   r<   r)   r]   r_   rM   msgs           r*   r   r     s    X ?//E&1K"LMMF8}a(FfXEVHfE&ID~e}.VeFm,, .fX1&:$#-.s   	A 	B$BBc           	   #   V   K   t         }| D ]  }|t         || ||            f  yw)a  Compute shortest path lengths between all nodes in a weighted graph.

    Parameters
    ----------
    G : NetworkX graph

    weight : string or function (default="weight")
        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_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)r   r   )r7   r)   r@   rs   s       r*   r   r   '  s6     d 4F 5$va623445s   ')c              #   D   K   t         }| D ]  }| || ||      f  yw)a
  Compute shortest paths between all nodes in a weighted graph.

    Parameters
    ----------
    G : NetworkX graph

    weight : string or function (default="weight")
        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 : iterator
        (source, dictionary) iterator with dictionary keyed by target and
        shortest path as the key value.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> path = dict(nx.all_pairs_bellman_ford_path(G))
    >>> 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   )r7   r)   rA   rs   s       r*   r   r   ^  s1     X +D -$q!F+,,-s    c                   	
 || vrt        j                  d| d      t        |       | j                         r?t	        fdt        j
                  | dd      D              rSt        j                  d      t	        fdt        j
                  | d      D              rt        j                  d      t        |       d	k(  r|d
i|difS | j                  	t        d      }t        j                  | |      
d
|<   |d
i	
fd}	
fd}|h}|r ||      } ||      }|rD ci c]  }|
|   
 c}

fS c c}w )aw
  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 (di)cycle, the
        algorithm raises an exception to indicate the presence of the
        negative (di)cycle.  Note: any negative weight edge in an
        undirected graph is a negative cycle.

        As of NetworkX v3.2, a zero weight cycle is no longer
        incorrectly reported as a negative weight 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 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 (di)cycle, it
    will not be detected.

    rC   rq   c              3   F   K   | ]  \  }}}} ||||i      d k    ywry   rz   r{   s        r*   r+   z"goldberg_radzik.<locals>.<genexpr>  r}   r~   Tr   r   c              3   @   K   | ]  \  }}} |||      d k    ywry   rz   r   s       r*   r+   z"goldberg_radzik.<locals>.<genexpr>  r   r   r   r$   Nr   r   c                    g }i }| D ]*  |v r	   t        fd   j                         D              r7t           j                               fg}h}d|<   |sa|d   \  }	 t        |      \  }}    ||      z   }|   }	||	k  r||	k  }
||<   |<   ||vrS|   t        |
      z   ||<   |j                  |t        |   j                               f       |j                  |       n0||v r,|   t        |
      z   ||   kD  rt        j                  d      |rʐ- |j                          |S # t        $ r6 |j                         |j                          |j                         Y  w xY w)zeTopologically sort nodes relabeled in the previous round and detect
        negative cycles.
        c              3   J   K   | ]  \  }} ||      z   |   k\    y wr   rz   )r'   r/   rl   r0   d_ur.   r)   s      r*   r+   z5goldberg_radzik.<locals>.topo_sort.<locals>.<genexpr>  s+     OTQ31a(AaD0Os    #r   r   )r   re   iterrd   StopIterationrf   popr   intr   rG   r   reverse)	relabeledto_scan	neg_countstackin_stackitr/   rl   td_vis_negr   r.   rg   r0   ra   r)   s              @@r*   	topo_sortz"goldberg_radzik.<locals>.topo_sort  s     	 &	OAI~A$COVAY__=NOO fQioo/012EsHIaLb	28DAq aD6!Q?*ds7WFAaDDG	)'0|c&k'A	!afQioo.?)@%AB Qh9Q<#f++E	RS+T
 !223MNN1 &	ON 	- % NN1%IIKOOA&	s   4E

;F	F	c                     t               }| D ]V  }|   }|   j                         D ]9  \  }} 
|||      }||z   |   k  s||z   |<   |	|<   |j                  |       ; X |S )z#Relax out-edges of relabeled nodes.)r   re   r   )r   r   r.   r   r/   rl   w_erg   r0   ra   r)   s          r*   relaxzgoldberg_radzik.<locals>.relax/  s    E	  	%AA$Cq	) %1Q1o9qt#9AaDDGMM!$%	% r2   )rG   rH   r8   r6   r   r   r   r   rc   r   r   r   )r7   r?   r)   r   r   r   r   r   r.   rg   r0   ra   s     `      @@@r*   r   r     sJ   b QoofX-GHIIa(F 
 //4H
 
 &&'ABBR"2C2CAD2QRR&&'ABB
1v{~{**VVF
,CaAAfID>D6p" I
I&'N	  QAaDA7N 	 s   3Ec                 \   | j                         dk(  ryd}|| v r
|dz  }|| v r
| j                  | D cg c]  }||f c}       	 t        | |||       	 | j                  |       yc c}w # t        j                  $ r Y | j                  |       yw xY w# | j                  |       w xY w)a  Returns 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.
    r   Fr   r$   )r)   r   T)sizeadd_edges_fromr   rG   r   remove_node)r7   r)   r   newnoders   s        r*   r   r   J  s    d 	vvx1} G
Q,1 Q, A.qwl./-wv	
 	
g /  	g 	
gs)   A)A. .BB BB B+c                    t        | |      }|g i}t        | |g||      }|t        j                  d      g }|t	        ||         fg}|h}|r|d   \  }}	||	v r)|j                  ||g       t	        t        |            }|S |	rV|	j                         }
|
|vr|j                  |
t	        ||
         f       |j                  |       |j                  |
       nP|j                          |r|j                          n-|| |   v r || ||      dk  r||gS t        j                  d      |rd}t        j                  |      )a9  Returns a cycle with negative total weight if it exists.

    Bellman-Ford is used to find shortest_paths. That algorithm
    stops if there exists a negative cycle. This algorithm
    picks up from there and returns the found negative cycle.

    The cycle consists of a list of nodes in the cycle order. The last
    node equals the first to make it a cycle.
    You can look up the edge weights in the original graph. In the case
    of multigraphs the relevant edge is the minimal weight edge between
    the nodes in the 2-tuple.

    If the graph has no negative cycle, a NetworkXError is raised.

    Parameters
    ----------
    G : NetworkX graph

    source: node label
        The search for the negative cycle will start from this 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.

    Examples
    --------
    >>> G = nx.DiGraph()
    >>> G.add_weighted_edges_from(
    ...     [(0, 1, 2), (1, 2, 2), (2, 0, 1), (1, 4, 2), (4, 0, -5)]
    ... )
    >>> nx.find_negative_cycle(G, 0)
    [4, 0, 1, 4]

    Returns
    -------
    cycle : list
        A list of nodes in the order of the cycle found. The last node
        equals the first to indicate a cycle.

    Raises
    ------
    NetworkXError
        If no negative cycle is found.
    )ra   zNo negative cycles detected.r   r   z(Negative cycle is detected but not foundz*negative cycle detected but not identified)r8   r   rG   NetworkXErrorlistextendreversedr   rf   r   r   )r7   r?   r)   ra   r/   	neg_cycler   rh   nodepredsnbrr   s               r*   r   r     sR   p a(FB<DAxd;Ay=>> Id1g E3D
Bie:dAY'Xi01I))+C$c4S	?34  &IIK!91a1!4q6M&&'QRR- 0 7C


s
##r2   c                    || vrt        j                  d| d      || vrt        j                  d| d      ||k(  rd|gfS t        | |      }i i g}||gi||gig}g g g}|di|dig}t               }t	        |d   dt        |      |f       t	        |d   dt        |      |f       | j                         r| j                  | j                  g}	n| j                  | j                  g}	g }
d}|d   rI|d   rCd|z
  }t        ||         \  }}}|||   v r+|||   |<   ||d|z
     v r|
fS |	|   |   j                         D ]  \  }}|dk(  r
 ||||      n	 ||||      }|"||   |   |z   }|||   v r|||   |   k  s@t        d      |||   vs|||   |   k  s^|||   |<   t	        ||   |t        |      |f       ||   |   |gz   ||   |<   ||d   v s||d   v s|d   |   |d   |   z   }|
g k(  s|kD  s|}|d   |   dd }|j                          |d   |   |dd z   }
 |d   r|d   rCt        j                  d| d	| d
      )a	  Dijkstra'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 or None to indicate a hidden edge.

    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 `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.

    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.

    In practice  bidirectional Dijkstra is much more than twice as fast as
    ordinary Dijkstra.

    Ordinary Dijkstra expands nodes in a sphere-like 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
    r   z is not in GzTarget r   r$   Nz,Contradictory paths found: negative weights?zNo path between z and r^   )rG   rH   r8   r   r   rd   is_directed_succ_predrc   r   re   rY   r   rK   )r7   r?   r<   r)   distsr]   rj   rh   ri   neighs	finalpathdirr_   rk   r/   	finaldistwr0   rm   vwLength	totaldistrevpaths                         r*   r
   r
     s   \ Qoox|<==Qoox|<==F8}a(FHEvh&6(!34E"XFQK&!%DAVAYDGV,-VAYDGV,-}}''177#&&!&&! I
C
)q	 #gvc{+q!c
?c
1a#g y))3KN((* 	>DAq&)Qh6!Q?F1aOD|Sz!}t+HE#JeCjm+$%STT$s)#x$s)A,'>'S	!xa!&<= %c
1 3c
1Q<AaL !%Q
T!WQZ 7I B)i*?$-	"'(1+a.)$)!HQK'!"+$=	-	>! )q	N 

.vheF81E
FFr2   c                      t         j                   d      } D ci c]  }|g  }}t               t         t	               ||      fd fd} D ci c]  }| ||       c}S c c}w c c}w )uL  Uses 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.

    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   )ra   r_   c                 0     | ||      |    z   |   z
  S r   rz   )r.   r/   r0   dist_bellmanr)   s      r*   
new_weightzjohnson.<locals>.new_weight	  s#    aAa0<?BBr2   c                 0    | | gi}t        | |       |S )N)r]   )rI   )r/   r]   r7   r   s     r*   	dist_pathzjohnson.<locals>.dist_path	  s!    QC!Q
%0r2   )r   r   r8   r   r   )r7   r)   r_   r/   ra   r   r   r   s   ``    @@r*   r    r    	  s    ~ ==ADaArEDa(F !DGV$TJLC
 &''Ay|O''!   (s   
A3 A8r   )Nr)   )NNr)   )NNNN)Nr)   F)NNNNT)NT)r)   T),__doc__collectionsr   heapqr   r   	itertoolsr   networkxrG   *networkx.algorithms.shortest_paths.genericr   __all__r8   _dispatchabler   r	   r   r   r   r   r   r   rI   rZ   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r
   r    rz   r2   r*   <module>r      s    #   U:%2P X&Z 'Zz X&LW 'LW^ X&=Q '=Q@ X&DX 'DXN X&b 'bJ X&F 'FR X&ND 'NDb X&tB 'tBn DHbJ X&EJ 'EJP X&A  'A H X&7> '7>t X&2< '2<j X&7<~ '~J 

	[F 
yx X&7 '7t X&CW 'CWL X&4 '4n X&;. ';.| X&Z. 'Z.z X&35 '35l X&-- '--` X&w 'wt X&C 'CL X&[$ '[$| X&PG 'PGf X&O( 'O(r2   