Skip to content

Commit 0690d30

Browse files
committed
committed from zkp
1 parent 6c18071 commit 0690d30

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

LeetCode/dijkstra.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import heapq
2+
3+
graph = {
4+
"A": {"B": 5, "C": 1},
5+
"B": {"A": 5, "C": 2, "D": 1},
6+
"C": {"A": 1, "B": 2, "D": 4, "E": 8},
7+
"D": {"B": 1, "C": 4, "E": 3, "F": 6},
8+
"E": {"C": 8, "D": 3},
9+
"F": {"D": 6}
10+
}
11+
12+
13+
def init_dist(graph, s):
14+
distance = {}
15+
for i in graph:
16+
if i == s:
17+
distance[i] = 0
18+
else:
19+
distance[i] = float('inf')
20+
return distance
21+
22+
23+
def dijkstra(graph, s):
24+
distance = init_dist(graph, s)
25+
seen = set()
26+
pq = []
27+
heapq.heappush(pq, (0, s))
28+
parent = {}
29+
while pq:
30+
dist, vertex = heapq.heappop(pq)
31+
seen.add(vertex)
32+
for w in graph[vertex]:
33+
if w not in seen:
34+
if dist + graph[vertex][w] < distance[w]:
35+
distance[w] = dist + graph[vertex][w]
36+
parent[w] = vertex
37+
heapq.heappush(pq, (distance[w], w))
38+
39+
return parent, distance
40+
41+
42+
if __name__ == "__main__":
43+
parent, distance = dijkstra(graph, "A")
44+
print(parent, distance)

0 commit comments

Comments
 (0)