This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ShortestPath-Dijkstra(G,s,t) | |
known = {s} | |
for i = 1 to n, dist[i] = ∞ | |
for each edge (s,v), dist[v] = w(s,v) | |
last = s | |
while (last != t) | |
select vnext, the unknown vertex minimizing dist[v] | |
for each edge (vnext,x), dist[x] = min[dist[x],dist[vnext] + w(vnext,x)] | |
last = vnext | |
known = known ∪ {vnext} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def shortest_path(source, target): | |
""" | |
Return the shortest path from the source to target. | |
""" | |
# Keeps track of the parent node for a node in the path between source and target. | |
parents = defaultdict(lambda: None) | |
# Keep track of the distance of each node to the source node | |
distances = {source: 0, target: INFINITY} | |