Skip to content

Instantly share code, notes, and snippets.

@matklad
Last active November 11, 2016 10:28
Show Gist options
  • Save matklad/e46c10e33271b76fa97ae11df0c25663 to your computer and use it in GitHub Desktop.
Save matklad/e46c10e33271b76fa97ae11df0c25663 to your computer and use it in GitHub Desktop.
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}
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