Skip to content

Instantly share code, notes, and snippets.

@e-mon
Last active August 29, 2015 14:11
Show Gist options
  • Save e-mon/439b08cbb54c663e4e19 to your computer and use it in GitHub Desktop.
Save e-mon/439b08cbb54c663e4e19 to your computer and use it in GitHub Desktop.
dijkstra
from heapq import heappush, heappop
def dijkstra(adjList,s):
num = len(adjList)
dist = [10**8 for i in range(num)]
prev = [-1 for i in range(num)]
queue = []
heappush(queue,(0,s))
dist[s] = 0
while len(queue) != 0:
v_cost, v = heappop(queue)
if dist[v] < v_cost:
continue
for u_cost, u in adjList[v]:
if u != v and u_cost + dist[v] < dist[u]:
prev[u] = v
dist[u] = u_cost + dist[v]
heappush(queue, (dist[u], u))
return dist,prev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment