Skip to content

Commit 9d970d2

Browse files
authored
Create Dijkstra-Algorithm.py
1 parent fcb6a69 commit 9d970d2

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

python/Dijkstra-Algorithm.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from heapq import *
2+
from collections import defaultdict
3+
4+
def dijkstra(edges, strat_node, end_node):
5+
g = defaultdict(list)
6+
for start, end, weight in edges:
7+
g[start].append((weight, end))
8+
q, visited = [(0, strat_node,())], set()
9+
while q:
10+
(cost,v1,path) = heappop(q)
11+
if v1 not in visited:
12+
visited.add(v1)
13+
path = (v1, path)
14+
if v1 == end_node:
15+
return (cost, path)
16+
for c, v2 in g.get(v1, ()):
17+
if v2 not in visited:
18+
heappush(q, (cost+c, v2, path))
19+
print (q)
20+
return float("inf")
21+
22+
if __name__ == "__main__":
23+
24+
edges = [
25+
("A", "B", 7),
26+
("A", "D", 5),
27+
("B", "C", 8),
28+
("B", "D", 9),
29+
("B", "E", 7),
30+
("C", "E", 5),
31+
("D", "E", 7),
32+
("D", "F", 6),
33+
("E", "F", 8),
34+
("E", "G", 9),
35+
("F", "G", 11)
36+
]
37+
38+
print ("=== Dijkstra ===")
39+
print ("A >> G:")
40+
print (dijkstra(edges, "A", "G"))

0 commit comments

Comments
 (0)