Skip to content

Instantly share code, notes, and snippets.

@nkt1546789
Last active August 29, 2015 14:12
Show Gist options
  • Save nkt1546789/068a15285bcaead3f56e to your computer and use it in GitHub Desktop.
Save nkt1546789/068a15285bcaead3f56e to your computer and use it in GitHub Desktop.
Implementation of Dijkstra's algorithm on Python
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