1
1
import heapq
2
2
import sys
3
3
4
- #First implementation of johnson algorithm
5
- #Steps followed to implement this algorithm is given in the below link:
6
- #https://brilliant.org/wiki/johnsons-algorithm/
4
+
5
+ # First implementation of johnson algorithm
6
+ # Steps followed to implement this algorithm is given in the below link:
7
+ # https://brilliant.org/wiki/johnsons-algorithm/
7
8
class JohnsonGraph :
8
9
def __init__ (self ):
9
10
self .edges = []
@@ -20,9 +21,9 @@ def add_edge(self, u, v, w):
20
21
21
22
# perform a dijkstra algorithm on a directed graph
22
23
def dijkstra (self , s ):
23
- distances = {vertex : sys .maxsize - 1 for vertex in self .graph }
24
- pq = [(0 ,s )]
25
-
24
+ distances = {vertex : sys .maxsize - 1 for vertex in self .graph }
25
+ pq = [(0 , s )]
26
+
26
27
distances [s ] = 0
27
28
while pq :
28
29
weight , v = heapq .heappop (pq )
@@ -36,9 +37,9 @@ def dijkstra(self, s):
36
37
heapq .heappush (pq , (distances [node ], node ))
37
38
return distances
38
39
39
- #carry out the bellman ford algorithm for a node and estimate its distance vector
40
- def bellman_ford (self , s ):
41
- distances = {vertex : sys .maxsize - 1 for vertex in self .graph }
40
+ # carry out the bellman ford algorithm for a node and estimate its distance vector
41
+ def bellman_ford (self , s ):
42
+ distances = {vertex : sys .maxsize - 1 for vertex in self .graph }
42
43
distances [s ] = 0
43
44
44
45
for u in self .graph :
@@ -47,10 +48,10 @@ def bellman_ford(self, s):
47
48
distances [v ] = distances [u ] + w
48
49
49
50
return distances
50
-
51
- #perform the johnson algorithm to handle the negative weights that
51
+
52
+ # perform the johnson algorithm to handle the negative weights that
52
53
# could not be handled by either the dijkstra
53
- #or the bellman ford algorithm efficiently
54
+ # or the bellman ford algorithm efficiently
54
55
def johnson_algo (self ):
55
56
self .add_vertices ("#" )
56
57
for v in self .graph :
0 commit comments