Log In Sign Up
Day 43

Day 43: Dijkstra's Algorithm

43/60 Days

Dijkstra’s Algorithm #

Welcome to Day 43 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore Dijkstra’s Algorithm, a fundamental graph algorithm used for finding the shortest paths between nodes in a graph.

What is Dijkstra’s Algorithm? #

Dijkstra’s Algorithm is a greedy algorithm that solves the single-source shortest path problem for a graph with non-negative edge weights. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later.

How Dijkstra’s Algorithm Works #

  1. Initialize distances to all vertices as infinite and distance to the source as 0.
  2. Create a set of unvisited vertices.
  3. For the current vertex, consider all its unvisited neighbors and calculate their tentative distances.
  4. When we are done considering all neighbors of the current vertex, mark it as visited and remove it from the unvisited set.
  5. If the destination vertex has been marked visited, we’re done.
  6. Otherwise, select the unvisited vertex with the smallest tentative distance, and repeat from step 3.

Implementation #

Let’s implement Dijkstra’s Algorithm in Python:

 1import heapq
 2 …