Last active
August 29, 2015 14:11
-
-
Save e-mon/439b08cbb54c663e4e19 to your computer and use it in GitHub Desktop.
dijkstra
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
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