Understanding Dijkstra’s Algorithm
January 25, 2025 | Algorithms
Dijkstra’s Algorithm is one of the most well-known algorithms in computer science, used to find the shortest path between nodes in a weighted graph. It’s widely applied in routing, mapping applications (like Google Maps), and network optimization.
Core Idea
Dijkstra’s algorithm starts at a source node and explores all reachable nodes while keeping track of the shortest known distance to each. It uses a greedy approach, always expanding the node with the smallest tentative distance.
How It Works
-
Assign every node a tentative distance:
0for the starting node.∞for all other nodes.
-
Mark all nodes as unvisited. Set the starting node as the current node.
-
For the current node, consider all of its unvisited neighbors and calculate their tentative distances.
- If the new distance is smaller, update it.
-
Once all neighbors are visited, mark the current node as visited.
-
Select the unvisited node with the smallest tentative distance as the new current node.
-
Repeat until all nodes are visited or the shortest path to the destination is found.
Example
Let’s find the shortest paths from node A.
Graph:
A → B (4)
A → C (2)
B → C (5)
B → D (10)
C → D (3)
Step-by-step
| Step | Current Node | Tentative Distances | Visited |
|---|---|---|---|
| 1 | A | A: 0, B: 4, C: 2, D: ∞ | A |
| 2 | C | A: 0, B: 4, C: 2, D: 5 | A, C |
| 3 | B | A: 0, B: 4, C: 2, D: 5 | A, C, B |
| 4 | D | A: 0, B: 4, C: 2, D: 5 | A, C, B, D |
Shortest distances from A:
- To B: 4
- To C: 2
- To D: 5
Implementation
function dijkstra(graph, start) {
const distances = {};
const visited = new Set();
// Initialize distances
for (const node in graph) {
distances[node] = node === start ? 0 : Infinity;
}
while (visited.size < Object.keys(graph).length) {
// Select unvisited node with smallest distance
const currentNode = Object.keys(distances)
.filter(n => !visited.has(n))
.reduce((a, b) => (distances[a] < distances[b] ? a : b));
// Visit neighbors
for (const [neighbor, weight] of Object.entries(graph[currentNode])) {
const newDistance = distances[currentNode] + weight;
if (newDistance < distances[neighbor]) {
distances[neighbor] = newDistance;
}
}
visited.add(currentNode);
}
return distances;
}
const graph = {
A: { B: 4, C: 2 },
B: { C: 5, D: 10 },
C: { D: 3 },
D: {}
};
console.log(dijkstra(graph, 'A'));
Expected Output
{ A: 0, B: 4, C: 2, D: 5 }
Time and Space Complexity
- Time Complexity:
O(V^2)(basic version). Using a priority queue, it becomesO((V + E) log V). - Space Complexity:
O(V)for storing distances and visited nodes.