Created
October 7, 2013 23:52
-
-
Save charlesreid1/6877075 to your computer and use it in GitHub Desktop.
Simplified Dijsktra's algorithm
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
# Simplified Dijsktra's Algorithm | |
# from http://code.activestate.com/recipes/119466/ | |
def shortest_path(G, start, end): | |
def flatten(L): # Flatten linked list of form [0,[1,[2,[]]]] | |
while len(L) > 0: | |
yield L[0] | |
L = L[1] | |
q = [(0, start, ())] # Heap of (cost, path_head, path_rest). | |
visited = set() # Visited vertices. | |
while True: | |
(cost, v1, path) = heapq.heappop(q) | |
if v1 not in visited: | |
visited.add(v1) | |
if v1 == end: | |
return list(flatten(path))[::-1] + [v1] | |
path = (v1, path) | |
for (v2, cost2) in G[v1].iteritems(): | |
if v2 not in visited: | |
heapq.heappush(q, (cost + cost2, v2, path)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment