-
Notifications
You must be signed in to change notification settings - Fork 4
/
shortest_path.py
67 lines (55 loc) · 1.27 KB
/
shortest_path.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
import sys
from pbft import *
class shortest_path:
def __init__(self,graph,src,dest):
self.graph = graph
self.INF = 10**18
self.src = src
self.dest = dest
self.edge = []
def getMinNode(self,dist,visited):
m = self.INF
for i in range(len(dist)):
if dist[i]<m and not visited[i]:
m,ind = dist[i],i
return ind
def get_path(self):
n = self.graph.N
visited = [False for i in range(n+1)]
dist = [self.INF for i in range(n+1)]
parent = [ -1 for i in range(n+1)]
dist[self.src] = 0
for i in range(n):
u = self.getMinNode(dist,visited)
visited[u] = True
for node,weight in self.graph.adj[u]:
if not visited[node]:
if dist[node]>dist[u]+weight:
dist[node] = dist[u]+weight
parent[node]= u
# print(dist)
# print(parent)
path = self.tracePath(parent)
# print("shortest path from src to dest from the graph: ",path)
return path,dist[self.dest]
def tracePath(self,parent):
curr = self.dest
path = []
while parent[curr]!=-1:
path.append(curr)
curr = parent[curr]
path.append(self.src)
path =path[::-1]
for i in range(1,len(path)):
x,y=path[i-1],path[i]
self.edge.append([x,y])
# print("PATHHH: ",self.edge)
return path
'''
1 2 3
2 4 6
3 2 6
X = 1,2,3
Y = 2,4,2
W = 3,6,6
'''