Dijkstra algorithm Implemetation

2025-08-221 min read

#Machine Learning#Data Science#Artificial Intelligence#Data Visualization#EDA#Part 1
Category:Machine Learning
Priyanshu Jha

Priyanshu Jha

Software Engineer

Cover

Key Points

  • Implentation
infinity = float('infinity')

def dijkstra(graph, starting_node):
  number_of_node = len(graph)
  visited_node = [False] * number_of_node
  shortest_distance = [infinity] * number_of_node
  previous_node = [None] * number_of_node

  shortest_distance[starting_node] = 0

  for _ in range(number_of_node):
      current_min_distance = infinity
      current_node = None

      for node in range(number_of_node):
          if not visited_node[node] and shortest_distance[node] < current_min_distance:
              current_min_distance = shortest_distance[node]
              current_node = node

      if current_node is None:
          break

      visited_node[current_node] = True

      for neighbour in range(number_of_node):
          weight = graph[current_node][neighbour]

          if weight != infinity and not visited_node[neighbour]:
              new_distance = shortest_distance[current_node] + weight

              if new_distance < shortest_distance[neighbour]:
                  shortest_distance[neighbour] = new_distance
                  previous_node[neighbour] = current_node

  return shortest_distance

i = infinity
graphdata = [
#    A     B    C    D
[0,   1,   4,   i],  # A
[1,   0,   2,   5],  # B
[4,   2,   0,   1],  # C
[i,   5,   1,   0]   # D
]

start_node = 0  # Starting from node A
costs = dijkstra(graphdata, start_node)

# Print costs in desired format
labels = ['A', 'B', 'C', 'D']
for idx in range(len(costs)):
  if idx != start_node:
      print(f"{labels[start_node]} to {labels[idx]}: {costs[idx]}")

Output

A to B: 1
A to C: 3
A to D: 4

Related Posts