Skip to content

Instantly share code, notes, and snippets.

@igorvanloo
Last active April 8, 2023 11:18
Show Gist options
  • Save igorvanloo/aa7685091b9ab54ad752efffb9bacc84 to your computer and use it in GitHub Desktop.
Save igorvanloo/aa7685091b9ab54ad752efffb9bacc84 to your computer and use it in GitHub Desktop.
Dijkstra's algorithm
def DijkstrasAlgorithm(graph, start_node = 0, INFINITY = 10**10):
#Takes a weighted adjacency list as input of the graph
n = len(graph)
D = [INFINITY]*n
D[start_node] = 0
cloud = [False for i in range(n)]
for i in range(n):
_, v = min((D[i], i) for i in range(n) if cloud[i] == False)
cloud[v] = True
#Follow pseudo-code
for b, w in graph[v]:
if cloud[b] == False:
t = D[v] + w
if t < D[b]:
D[b] = t
flag = True
for i in range(n):
if cloud[i] == False:
if D[i] != INFINITY:
flag = False
break
if flag:
break
return D
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment