- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathdial_algorithm.py
More file actions
Latest commit
56 lines (56 loc) · 1.25 KB
/
Copy pathdial_algorithm.py
File metadata and controls
56 lines (56 loc) · 1.25 KB
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
fromtypingimportList, Tuple
INF=0x3f3f3f3f
classGraph:
def__init__(self, V: int):
self.V=V
self.adj= [[] for_inrange(V)]
defaddEdge(self, u: int, v: int, w: int):
self.adj[u].append((v, w))
self.adj[v].append((u, w))
defshortestPath(self, src: int, W: int):
dist= [[INF, None] for_inrange(self.V)]
dist[src][0] =0
B= [[] for_inrange(W*self.V+1)]
B[0].append(src)
idx=0
whileTrue:
whilelen(B[idx]) ==0andidx<W*self.V:
idx+=1
ifidx==W*self.V:
break
u=B[idx][0]
B[idx].pop(0)
forv, weightinself.adj[u]:
du=dist[u][0]
dv=dist[v][0]
ifdv>du+weight:
ifdv!=INF:
B[dv].remove(v)
dist[v][0] =du+weight
dv=dist[v][0]
B[dv].append(v)
dist[v][1] =len(B[dv]) -1
print("Distance from Source")
foriinrange(self.V):
print(f"{i}{dist[i][0]}")
defmain():
V=9
W=14
g=Graph(V)
g.addEdge(0, 1, 4)
g.addEdge(0, 7, 8)
g.addEdge(1, 2, 8)
g.addEdge(1, 7, 11)
g.addEdge(2, 3, 7)
g.addEdge(2, 8, 2)
g.addEdge(2, 5, 4)
g.addEdge(3, 4, 9)
g.addEdge(3, 5, 14)
g.addEdge(4, 5, 10)
g.addEdge(5, 6, 2)
g.addEdge(6, 7, 1)
g.addEdge(6, 8, 6)
g.addEdge(7, 8, 7)
g.shortestPath(0, W)
if__name__=="__main__":
main()