-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdjikstras.py
40 lines (38 loc) · 1009 Bytes
/
djikstras.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
import heapq as hq
import math
def dijkstra(G, s):
n = len(G)
visited = [False]*n
weights = [math.inf]*n
path = [None]*n
queue = []
weights[s] = 0
hq.heappush(queue, (0, s))
while len(queue) > 0:
g, u = hq.heappop(queue)
visited[u] = True
for v, w in G[u]:
if not visited[v]:
f = g + w
if f < weights[v]:
weights[v] = f
path[v] = u
hq.heappush(queue, (f, v))
return path, weights
if __name__ == "__main__":
graph = {
'A': {'B': 2, 'C': 4},
'B': {'A': 2, 'C': 3, 'D': 8},
'C': {'A': 4, 'B': 3, 'E': 5, 'D': 2},
'D': {'B': 8, 'C': 2, 'E': 11, 'F': 22},
'E': {'C': 5, 'D': 11, 'F': 1},
'F': {'D': 22, 'E': 1}
}
start = 'A'
end = 'F'
G = [[(1, 6), (3, 7)],
[(2, 5), (3, 8), (4, -4)],
[(1, -2), (4, 7)],
[(2, -3), (4, 9)],
[(0, 2)]]
print(dijkstra(G, 0))