File tree 1 file changed +45
-0
lines changed
Graph_Algorithms/src/Dijkstra
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ """Dijkstra's algorithm."""
2
+
3
+ import math
4
+
5
+
6
+ class Vertex :
7
+
8
+ def __init__ (self , id ):
9
+ self .id = str (id )
10
+ self .distance = 0
11
+ self .neighbors = []
12
+ self .edges = {} # {vertex:distance}
13
+
14
+ def __lt__ (self , other ):
15
+ """Comparison rule to < operator."""
16
+ return self .distance < other .distance
17
+
18
+ def __repr__ (self ):
19
+ """Return the vertex id."""
20
+ return self .id
21
+
22
+ def add_neighbor (self , vertex ):
23
+ """Add a pointer to a vertex at neighbor's list."""
24
+ self .neighbors .append (vertex )
25
+
26
+ def add_edge (self , vertex , weight ):
27
+ """Destination vertex and weight."""
28
+ self .edges [vertex .id ] = weight
29
+
30
+
31
+ def dijkstra (graph , source , destiny ):
32
+ """Dijkstra's Algorithm."""
33
+ q = []
34
+ for v in graph :
35
+ v .distance = math .inf
36
+ q .append (v )
37
+ source .distance = 0
38
+ while q :
39
+ v = min (q )
40
+ q .remove (v )
41
+ for u in v .neighbors :
42
+ new = v .distance + v .edges [u .id ]
43
+ if new < u .distance :
44
+ u .distance = new
45
+ return destiny .distance
You can’t perform that action at this time.
0 commit comments