-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDIJSKRA'S.PY
68 lines (56 loc) · 2.02 KB
/
DIJSKRA'S.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
# graph
# -----------------------------------------------------------------------------------------------------------
# 0-------[10]------1\
# | / | \
# | / | [9]
# [30] [20] [5] 2
# | / | /
# | / | [8]
# 4 ------[40]------3 /
#
# -----------------------------------------------------------------------------------------------------------
# each vertex has object of class vertex
# 0 -> [vertex,vertex]
# vertex = vertex-0 , weight-10 , edge-1
import queue
class Graph:
def __init__(self,graph,size,weight_matrix):
self.edge = graph
self.size = size
self.weight_matrix = weight_matrix
def dikstra(self,src):
pq = queue.PriorityQueue()
visited = [False]*self.size
visited[src]=True
pq.put((0,src))
shortest_paths = ""
while pq.queue:
nodes_weight,node = pq.get()
visited[node]=True
for each_node in self.edge[node]:
if visited[each_node]==False:
u = node
v = each_node
weight = min(self.weight_matrix[u][v] + nodes_weight,self.weight_matrix[u][v])
pq.put((weight,each_node))
msg = f"{u} to {v}"
shortest_paths+=msg + " -> " + str(weight) + "\n"
print(shortest_paths)
if __name__ == '__main__':
inf = 99999999
graph = {
0:set([1,4]),
1:set([0,2,3,4]),
2:set([1,3]),
3:set([1,2,4]),
4:set([0,1,3]),
}
weight_list = [[inf,10,inf,inf,30],
[10,inf,9,5,20],
[inf,9,inf,8,inf],
[inf,5,8,inf,40],
[inf,20,inf,40,inf]]
size = 5
g = Graph(graph,size,weight_list)
# print("edge",g.edge)
g.dikstra(0)