-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstra.py
More file actions
45 lines (28 loc) · 791 Bytes
/
dijkstra.py
File metadata and controls
45 lines (28 loc) · 791 Bytes
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
from collections import defaultdict as dt
from heapq import heappush, heappop
from math import log2
class Dijsktra:
def __init__(self,nodes):
self.graph=dt(lambda:[])
self.nodes=nodes
def addedge(self,u,v,d):
self.graph[u].append((v,d))
self.graph[v].append((u,d))
def util(self,start):
distance=[float('inf')]*(self.nodes)
distance[start]=0
priority=[(0,start)]
while priority:
d,u=heappop(priority)
if d==distance[u]: #to only check min distance node in priority queue
for v,d in self.graph[u]:
if distance[u]+d<distance[v]:
distance[v]=distance[u]+d
heappush(priority,(distance[v],v))
return distance
if __name__ == '__main__':
g=Dijsktra(3)
g.addedge(0,1,0.5)
g.addedge(1,2,0.5)
g.addedge(0,2,0.25)
print(g.util(0))