@@ -700,6 +700,8 @@ def shortest_paths(graph: Graph, algorithm: str,
700
700
'bellman_ford' -> Bellman-Ford algorithm as given in [1].
701
701
702
702
'dijkstra' -> Dijkstra algorithm as given in [2].
703
+
704
+ 'queue_improved_bellman_ford' -> Queue Improved Bellman-Ford algorithm as given in [3].
703
705
source: str
704
706
The name of the source the node.
705
707
target: str
@@ -742,6 +744,7 @@ def shortest_paths(graph: Graph, algorithm: str,
742
744
743
745
.. [1] https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm
744
746
.. [2] https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
747
+ .. [3] https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm#Improvements
745
748
"""
746
749
raise_if_backend_is_not_python (
747
750
shortest_paths , kwargs .get ('backend' , Backend .PYTHON ))
@@ -811,6 +814,37 @@ def _dijkstra_adjacency_list(graph: Graph, start: str, target: str):
811
814
812
815
_dijkstra_adjacency_matrix = _dijkstra_adjacency_list
813
816
817
+ def _queue_improved_bellman_ford_adjacency_list (graph : Graph , source : str , target : str ) -> tuple :
818
+ distances , predecessor , visited = {}, {}, {}
819
+
820
+ for v in graph .vertices :
821
+ distances [v ] = float ('inf' )
822
+ predecessor [v ] = None
823
+ visited [v ] = False
824
+ distances [source ] = 0
825
+
826
+ que = Queue ([source ])
827
+
828
+ while que :
829
+ u = que .popleft ()
830
+ visited [u ] = False
831
+ neighbors = graph .neighbors (u )
832
+ for neighbor in neighbors :
833
+ v = neighbor .name
834
+ edge_str = u + '_' + v
835
+ if distances [u ] != float ('inf' ) and distances [u ] + graph .edge_weights [edge_str ].value < distances [v ]:
836
+ distances [v ] = distances [u ] + graph .edge_weights [edge_str ].value
837
+ predecessor [v ] = u
838
+ if not visited [v ]:
839
+ que .append (v )
840
+ visited [v ] = True
841
+
842
+ if target != "" :
843
+ return (distances [target ], predecessor )
844
+ return (distances , predecessor )
845
+
846
+ _queue_improved_bellman_ford_adjacency_matrix = _queue_improved_bellman_ford_adjacency_list
847
+
814
848
def all_pair_shortest_paths (graph : Graph , algorithm : str ,
815
849
** kwargs ) -> tuple :
816
850
"""
0 commit comments