Dijkstra's algorithm explained step-by-step: greedy relaxation, min-priority queue usage, shortest path routing, complexity, and implementation.
Dijkstra's Algorithm finds the minimum distance from a single source vertex to every other vertex in a weighted directed or undirected graph with non-negative edge weights.
Using a Min-Priority Queue (or Min-Heap), Dijkstra greedily selects the unvisited node with the smallest tentative distance, relaxes its outgoing edges, and updates distances to adjacent nodes.
Set distance to start node as 0 and all other vertices to Infinity. Insert (0, startNode) into a Min-Priority Queue.
Pop the node with the smallest tentative distance from the Min-Priority Queue. If already processed, skip it.
For each neighbor, check if distanceToCurrent + weight(current, neighbor) < distanceToNeighbor. If so, update distanceToNeighbor and push to Min-Priority Queue.
Continue until all reachable nodes have been processed. The distance array now contains the optimal shortest paths.
1function dijkstra(graph, startNode) {2 const distances = {};3 const visited = new Set();4 5 // Simple Min-Priority Queue helper6 for (const node in graph) {7 distances[node] = Infinity;8 }9 distances[startNode] = 0;10 11 const pq = [[0, startNode]]; // [distance, node]12 13 while (pq.length > 0) {14 // Sort to extract minimum (Min-Heap simulation)15 pq.sort((a, b) => a[0] - b[0]);16 const [currDist, u] = pq.shift();17 18 if (visited.has(u)) continue;19 visited.add(u);20 21 for (const neighbor in graph[u]) {22 const weight = graph[u][neighbor];23 const alt = currDist + weight;24 25 if (alt < distances[neighbor]) {26 distances[neighbor] = alt;27 pq.push([alt, neighbor]);28 }29 }30 }31 32 return distances;33}34 35// Example graph:36// const graph = {37// A: { B: 4, C: 2 },38// B: { C: 1, D: 5 },39// C: { B: 1, D: 8, E: 10 },40// D: { E: 2 },41// E: {}42// };43// dijkstra(graph, 'A'); // { A: 0, B: 3, C: 2, D: 8, E: 10 }Play through every comparison, swap, and state change, adjust the speed, or enter custom inputs to test edge cases.
The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Interactive node & edge state graph traversal explorer
Test your understanding of Dijkstra's Algorithm complexity and step mechanics.
Q1.Why does Dijkstra's Algorithm fail or enter infinite loops with negative edge weights?
Q2.What is the optimal time complexity of Dijkstra when implemented with a Fibonacci Heap or Binary Min-Heap?
Apply Dijkstra's Algorithm to real coding interview questions.
Calculate time taken for a signal to reach all nodes in a network starting from node K.
Find a route in a 2D height grid that minimizes the maximum absolute difference in heights between consecutive cells.