Last active
November 11, 2016 10:28
-
-
Save matklad/e46c10e33271b76fa97ae11df0c25663 to your computer and use it in GitHub Desktop.
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 bfs(graph, start): | |
work = {start} | |
dist = {} | |
current_dist = 0 | |
while work: | |
for u in work: | |
dist[u] = current_dist | |
work = {nb for u in work | |
for nb in graph[u] | |
if v not in dist} |
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(graph, start): | |
dist = {start: 0} | |
border = {u: weight for (u, weight) in graph[start]} | |
while border: | |
u = min(border, key=lambda u: border[u]) | |
dist[u] = border[u] | |
for (v, weight) in graph[u]: | |
if v in dist: | |
assert dist[u] + weight >= dist[v] | |
continue | |
border[v] = min( | |
dist[u] + weight, | |
border.get(v, float("inf")) | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment