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#
- Initialize distances to all vertices as infinite and distance to the source as 0.
- Create a set of unvisited vertices.
- For the current vertex, consider all its unvisited neighbors and calculate their tentative distances.
- When we are done considering all neighbors of the current vertex, mark it as visited and remove it from the unvisited set.
- If the destination vertex has been marked visited, we’re done.
- 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
3def dijkstra(graph, start): …Keep your momentum going
Create a free account to unlock the full lesson, all 60 days, and track your progress as you go.
- Full access to all 60 daily lessons
- Track completion and build a daily streak
- Get interview-ready, one algorithm at a time
Join 2,900+ learners · 4.8/5 average rating