Skip to content

Commit 055c642

Browse files
authored
Update dijkstra.py
1 parent 2ffdabf commit 055c642

File tree

1 file changed

+13
-35
lines changed

1 file changed

+13
-35
lines changed

src/python/dijkstra.py

+13-35
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,27 @@
11
import heapq
22

3+
34
class Graph:
4-
55
def __init__(self, edges: list):
66
self.adj = [[] for _ in range(len(edges))]
77
self.dist = [99999 for _ in range(len(edges))]
88
self.add_edges(edges)
99

1010
def add_edges(self, edges: list) -> None:
11-
1211
for i in range(len(edges)):
1312
for j in range(len(edges[i])):
1413
self.__add_edge(i, edges[i][j])
1514

1615
def __add_edge(self, u: int, v: int) -> None:
17-
"""Adds the edge to the adjacency matrix.
18-
19-
Args:
20-
u (int): Vertex u.
21-
v (int): Vertex v.
22-
"""
2316
if v[0] not in self.adj[u]:
2417
self.adj[u].append([v[1], v[0]])
2518

2619
def _weight_between_u_and_v(self, u: int, v: int) -> float:
27-
"""Returns the weight between vertices u and v.
28-
29-
Args:
30-
u (int): Vertex u.
31-
v (int): Vertex v.
32-
33-
Returns:
34-
float: Weight between u and v.
35-
"""
3620
for vertex in self.adj[v[1]]:
3721
if vertex[1] == u:
3822
return vertex[0]
3923

4024
def dijkstra(self, start: int) -> list:
41-
"""Returns the list of distances from vertex start to all vertices.
42-
43-
Args:
44-
start (int): Initial vertex.
45-
46-
Returns:
47-
list: List of distances.
48-
"""
4925
distance = self.dist.copy()
5026
S = set() # Set of explored vertices
5127
distance[start] = 0
@@ -66,14 +42,16 @@ def dijkstra(self, start: int) -> list:
6642

6743
return distance
6844

69-
edges = [
70-
[[1, 1], [2, 0.3], [5, 0.2]], # Neighbors of vertex 0.
71-
[[0, 1], [2, 0.5]], # Neighbors of vertex 1.
72-
[[0, 0.3], [1, 0.5], [3, 1.5], [4, 2]], # Neighbors of vertex 2.
73-
[[2, 1.5], [4, 1.3], [5, 0.8]], # Neighbors of vertex 3.
74-
[[2, 2], [3, 1.3]], # Neighbors of vertex 4.
75-
[[0, 0.2], [3, 0.8]], # Neighbors of vertex 5.
76-
]
7745

78-
graph = Graph(edges)
79-
print(graph.dijkstra(0))
46+
if __name__ == "__main__":
47+
edges = [
48+
[[1, 1], [2, 0.3], [5, 0.2]], # Neighbors of vertex 0.
49+
[[0, 1], [2, 0.5]], # Neighbors of vertex 1.
50+
[[0, 0.3], [1, 0.5], [3, 1.5], [4, 2]], # Neighbors of vertex 2.
51+
[[2, 1.5], [4, 1.3], [5, 0.8]], # Neighbors of vertex 3.
52+
[[2, 2], [3, 1.3]], # Neighbors of vertex 4.
53+
[[0, 0.2], [3, 0.8]], # Neighbors of vertex 5.
54+
]
55+
56+
graph = Graph(edges)
57+
print(graph.dijkstra(0))

0 commit comments

Comments
 (0)