-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra_shortest_path_algorithm.py
83 lines (60 loc) · 2.33 KB
/
dijkstra_shortest_path_algorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import math
class DijkstraShortestPathAlgorithm:
"""
Dijkstra's shortest path algorithm
Implementation of Dijkstra's shortest path algorithm to find the shortest distance
Attributes:
graph (list(list)) : adjacency matrix of the graph
"""
graph = [[]]
def __init__(self, graph):
self.graph = graph
def get_all_nodes(self, source, dist):
all_nodes = {}
for vertex in self.graph:
vertex_index = self.graph.index(vertex)
if vertex_index != source:
dist.append(math.inf)
all_nodes[str(vertex_index)] = vertex_index
return all_nodes
def compute_minimum_distance(self, source):
visited = set()
dist = []
dist.append(0)
all_nodes = self.get_all_nodes(source, dist)
while len(all_nodes) > 0:
min_list = []
for index, distances in enumerate(dist):
if index in visited:
continue
min_list.append(distances)
min_value = min(min_list)
shortest_dist_index = 0
for indexes, distances in enumerate(dist):
if distances == min_value and indexes not in visited:
shortest_dist_index = indexes
vertex = self.graph[shortest_dist_index]
all_nodes.pop(str(shortest_dist_index))
visited.add(shortest_dist_index)
for index, _ in enumerate(vertex):
if str(index) not in all_nodes:
continue
computed_dist = dist[shortest_dist_index] + self.graph[shortest_dist_index][index]
if dist[shortest_dist_index] < computed_dist < dist[index]:
dist[index] = computed_dist
return dist
def main():
graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]]
obj = DijkstraShortestPathAlgorithm(graph)
dist = obj.compute_minimum_distance(0)
print(dist)
if __name__ == "__main__":
main()