Skip to content

Instantly share code, notes, and snippets.

@DiracSpace
Created March 6, 2021 23:43
Show Gist options
  • Save DiracSpace/a3b861ddac5b7e060ee98a1a1858edaf to your computer and use it in GitHub Desktop.
Save DiracSpace/a3b861ddac5b7e060ee98a1a1858edaf to your computer and use it in GitHub Desktop.
import heapq
def dijkstra(graph, start, end):
heap = [(0, start)]
visited = set()
while heap:
(cost, u) = heapq.heappop(heap)
if u in visited:
continue
visited.add(u)
if u == end:
return cost
for v, c in graph[u]:
if v in visited:
continue
next = cost + c
heapq.heappush(heap, (next, v))
return -1
G = {
"A": [["B", 2], ["C", 5]],
"B": [["A", 2], ["D", 3], ["E", 1], ["F", 1]],
"C": [["A", 5], ["F", 3]],
"D": [["B", 3]],
"E": [["B", 4], ["F", 3]],
"F": [["C", 3], ["E", 3]],
}
G2 = {
"B": [["C", 1]],
"C": [["D", 1]],
"D": [["F", 1]],
"E": [["B", 1], ["F", 3]],
"F": [],
}
G3 = {
"B": [["C", 1]],
"C": [["D", 1]],
"D": [["F", 1]],
"E": [["B", 1], ["G", 2]],
"F": [],
"G": [["F", 1]],
}
shortDistance = dijkstra(G, "E", "C")
print(shortDistance) # E -- 3 --> F -- 3 --> C == 6
shortDistance = dijkstra(G2, "E", "F")
print(shortDistance) # E -- 3 --> F == 3
shortDistance = dijkstra(G3, "E", "F")
print(shortDistance) # E -- 2 --> G -- 1 --> F == 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment