• Finds shortest distances between source and other nodes in
  • for each with length of shortest path from to
    • Initially, is 0, other vertices have length of infinity
  • Boolean array for each which stores if is marked
  • At each iteration, unmarked with lowest is picked
    • In first iteration, starting is selected
    • Selected vertex is marked in
    • From , relaxations are performed to reduce distance
      • For each edge of form , algorithm tries to improve
      • If length of current edge is , relaxation is
    • After iterations, all vertices will be marked
  • Values are the shortest paths, infinite values are unreachable
import math
 
# nodes
nodes = [
    [(1, 5), (2, 10), (5, 15)],
    [(5, 5)],
    [(3, 2)],
    [], [], [],
]
n = len(nodes)
 
# distances
d = [math.inf if i != 0 else 0 for i in range(n)]
 
# markings
u = [False for _ in range(n)]
 
# parents
p = [-1 for _ in range(n)]
 
for _ in range(n):
    v = None
 
    # find lowest v which is unmarked
    for i, vd in enumerate(d):
        if not u[i] and (v == None or vd < d[v]):
            v = i
 
    u[v] = True
 
    # iterate over edges
    for edge in nodes[v]:
        to = edge[0]
        length = edge[1]
 
        # set new distance if lower
        if d[v] + length < d[to]:
            d[to] = d[v] + length
            p[to] = v
 
print(d)
print(p)