Created
October 20, 2012 08:38
-
-
Save irachex/3922694 to your computer and use it in GitHub Desktop.
Dijkstra (with Heap optimized) in 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
from heapq import heappush, heappop | |
def dijkstra(N, S, edges): | |
d = [INF for i in range(N)] | |
d[S] = 0 | |
h = [] | |
heappush(h, (0, S)) | |
for i in range(N - 1): | |
min_dist, k = 0, 0 | |
if not h: break | |
while h: | |
min_dist, k = heappop(h) | |
if min_dist == d[k]: break | |
for j, w in edges[k]: | |
if d[j] > d[k] + w: | |
d[j] = d[k] + w | |
heappush(h, (d[j], j)) | |
return d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What did your edges consist of?