A mathematician named Edsger Dijkstra
invented this algorithm in 1959 while
thinking about the shortest route between
two cities in the Netherlands.
65 years later it runs inside Google Maps
billions of times every day.
Why It Still Works
Dijkstra solves the single-source shortest
path problem with one brilliant greedy insight:
When you process the closest unvisited node
first — its distance is permanently optimal.
No undiscovered shorter path can exist.
\javascript
// Always pick closest unvisited node
let u = -1;
NODES.forEach((n) => {
if (!visited.has(n.id) &&
(u === -1 || dist[n.id] < dist[u])) {
u = n.id;
}
});
\\
Edge Relaxation
For every neighbor of the current node —
check if going through this node creates
a shorter path:
\javascript
for (const { node: v, weight } of adj[u]) {
if (!visited.has(v) &&
dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
}
}
\\
If yes — update. This is called relaxation.
Watch it happen in real time in the
visualization below.
The One Weakness
Negative edge weights break the greedy
assumption entirely. A negative edge
could always create a shorter path through
an already finalized node.
For negative weights — Bellman-Ford
takes over.
Watch It Live
What's Next
Hash Tables — O(1) lookup explained
visually. How JavaScript objects work
under the hood in 2 minutes.
Subscribe to AlgoCanvas:
👉 youtube.com/@AlgoCanvas
Top comments (0)