1
1
from math import inf
2
2
3
+
3
4
class Dijkstra :
4
5
def __init__ (self , graph ):
5
6
self .graph = graph
6
7
self .n_vertices = len (graph )
7
8
8
- def print_distance (self , dist , target = None ):
9
+ def print_distance (self , dist , target = None , show_print = None ):
9
10
if target :
10
- print ("distance:" , dist [target ])
11
+ if show_print :
12
+ print ("distance:" , dist [target ])
11
13
return dist [target ]
12
-
13
- print ("Vertex \t Distance from Source" )
14
- for node in range (self .n_vertices ):
15
- print (node , "\t \t " , dist [node ])
14
+ if show_print :
15
+ print ("Vertex \t Distance from Source" )
16
+ for node in range (self .n_vertices ):
17
+ print (node , "\t \t " , dist [node ])
16
18
17
19
def print_path (self , path , target ):
18
20
queue = [target ]
19
21
build_path = []
20
22
while True :
21
- prev = queue .pop (0 )
23
+ prev = queue .pop (0 )
22
24
build_path .append (prev )
23
25
if path [prev ] is None :
24
26
break
@@ -27,33 +29,30 @@ def print_path(self, path, target):
27
29
print ("path:" , " -> " .join ([str (i ) for i in build_path ]))
28
30
29
31
def min_distance (self , dist , visited ):
30
- min = inf # Initialize minimum distance for next node
31
- for v in range (self .n_vertices ): # get nearest vertex not visited
32
- if dist [v ] < min and visited [v ] == False :
32
+ min = inf # Initialize minimum distance for next node
33
+ for v in range (self .n_vertices ): # get nearest vertex not visited
34
+ if dist [v ] < min and visited [v ] is False :
33
35
min = dist [v ]
34
36
min_index = v
35
-
36
37
return min_index
37
38
38
- def dijkstra (self , src , target = None ): # O(n2)
39
+ def dijkstra (self , src , target = None , show_print = None ): # O(n2)
39
40
visited = [False ] * self .n_vertices
40
41
dist = [inf ] * self .n_vertices
41
42
dist [src ] = 0
42
- path_prev = {src :None }
43
-
43
+ path_prev = {src : None }
44
44
for _ in range (self .n_vertices ):
45
45
# Get the minimum distance vertex not visited yet.
46
46
# u is always equal to src in first iteration.
47
47
u = self .min_distance (dist , visited )
48
48
visited [u ] = True
49
-
50
49
# Update distance value of the adjacent vertices
51
50
for v in range (self .n_vertices ):
52
- if (self .graph [u ][v ] > 0 and # Check if has edge
53
- visited [v ] == False and
51
+ if (self .graph [u ][v ] > 0 and # Check if has edge
52
+ visited [v ] is False and
54
53
dist [v ] > dist [u ] + self .graph [u ][v ]):
55
54
dist [v ] = dist [u ] + self .graph [u ][v ]
56
55
path_prev .update ({v : u })
57
-
58
- self .print_path (path_prev , target )
59
- return self .print_distance (dist , target )
56
+ if show_print :
57
+ self .print_path (path_prev , target )
58
+ return self .print_distance (dist , target , show_print )
0 commit comments