Last active
August 29, 2015 14:12
-
-
Save nkt1546789/068a15285bcaead3f56e to your computer and use it in GitHub Desktop.
Implementation of Dijkstra's algorithm on Python
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 dijkstra(M,s,SELF=0,NOTCONNECTED=-1): | |
""" | |
M: adjacency matrix | |
s: starting point | |
""" | |
n=len(M) | |
table=[float("inf") for i in xrange(n)] | |
done=set() | |
heap=[] | |
heappush(heap,[0,s]) | |
while heap: | |
v=heappop(heap) | |
if v[1] in done: continue | |
if table[v[1]]>v[0]: table[v[1]]=v[0] | |
done.add(v[1]) | |
for i in xrange(n): | |
if M[v[1]][i]==SELF or M[v[1]][i]==NOTCONNECTED: continue | |
heappush(heap,[v[0]+M[v[1]][i],i]) | |
return table |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment