-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshortestPath.py
77 lines (65 loc) · 1.38 KB
/
shortestPath.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
#stack queue recursion and introduction
from math import inf
from queue import PriorityQueue
G = {
'A': {
'B': 3,
'C': 1
},
'B': {
'A': 3,
'E': 1,
'D': 5,
'C': 7
},
'C': {
'A': 1,
'D': 2
},
'D': {
'C': 2,
'B': 5,
'E': 7,
},
'E': {
'B': 1,
'D': 7
}
}
def init(G, start):
cost = dict()
prev = dict()
for vertex in G:
cost[vertex] = inf
prev[vertex] = ""
cost[start] = 0
return cost, prev
c, d = init(G, 'A')
def relax(G, u, v, cost, prev):
if (cost[v] > cost[u] + G[u][v]):
cost[v] = cost[u] + G[u][v]
prev[v] = u
return cost, prev
def DJ(G, start):
cost, prev = init(G, start)
visited = list()
Q = PriorityQueue()
for vertex in G:
Q.put((cost[vertex], vertex))
while (Q.empty() == False):
c, u = Q.get()
visited.append(u)
for c in G[u]:
if c not in visited:
cost, prev = relax(G, u, c,cost, prev)
return cost, prev
def constructPath(prev, start, end ):
path = end
while(prev[end] != ''):
path= prev[end]+'->'+path
end = prev[end]
return path
print(DJ(G, 'A'))
cost, prev= DJ(G, 'A')
for vertex in G:
print("Path from ", 'A', "to ", vertex, "is ", constructPath(prev, 'A', vertex))