Skip to content

Commit 36a6300

Browse files
authored
Merge pull request #166 from dunderbruno/master
Dijkstra's algorithm
2 parents ddac11f + 7e22355 commit 36a6300

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

0 commit comments

Comments
 (0)