Home >Web Front-end >JS Tutorial >Understanding Dijkstras Algorithm: From Theory to Implementation
Dijkstra's algorithm is a classic pathfinding algorithm used in graph theory to find the shortest path from a source node to all other nodes in a graph. In this article, we’ll explore the algorithm, its proof of correctness, and provide an implementation in JavaScript.
Dijkstra's algorithm is a greedy algorithm designed to find the shortest paths from a single source node in a weighted graph with non-negative edge weights. It was proposed by Edsger W. Dijkstra in 1956 and remains one of the most widely used algorithms in computer science.
Initialize distances:
Use a priority queue to store nodes based on their distances.
Repeatedly extract the node with the smallest distance and relax its neighbors.
where (s) is the source node, and (v) represents any other node.
Why It Works: Relaxation ensures that we always find the shortest path to a node by progressively updating the distance when a shorter path is found.
Queue Operation:
We prove the correctness of Dijkstra’s algorithm using strong induction.
Strong induction is a variant of mathematical induction where, to prove a statement (P(n)) , we assume the truth of (P(1),P(2),…,P(k)) to prove (P(k 1)) . This differs from regular induction, which assumes only (P(k)) to prove (P(k 1)) . Explore it in greater detail in my other post.
Base Case:
The source node
(s)
is initialized with
dist(s)=0
, which is correct.
Inductive Hypothesis:
Assume all nodes processed so far have the correct shortest path distances.
Inductive Step:
The next node
(u)
is dequeued from the priority queue. Since
dist(u)
is the smallest remaining distance, and all previous nodes have correct distances,
dist(u)
is also correct.
Prerequisites (Priority Queue):
// Simplified Queue using Sorting // Use Binary Heap (good) // or Binomial Heap (better) or Pairing Heap (best) class PriorityQueue { constructor() { this.queue = []; } enqueue(node, priority) { this.queue.push({ node, priority }); this.queue.sort((a, b) => a.priority - b.priority); } dequeue() { return this.queue.shift(); } isEmpty() { return this.queue.length === 0; } }
Here’s a JavaScript implementation of Dijkstra’s algorithm using a priority queue:
function dijkstra(graph, start) { const distances = {}; // hold the shortest distance from the start node to all other nodes const previous = {}; // Stores the previous node for each node in the shortest path (used to reconstruct the path later). const pq = new PriorityQueue(); // Used to efficiently retrieve the node with the smallest tentative distance. // Initialize distances and previous for (let node in graph) { distances[node] = Infinity; // Start with infinite distances previous[node] = null; // No previous nodes at the start } distances[start] = 0; // Distance to the start node is 0 pq.enqueue(start, 0); while (!pq.isEmpty()) { const { node } = pq.dequeue(); // Get the node with the smallest tentative distance for (let neighbor in graph[node]) { const distance = graph[node][neighbor]; // The edge weight const newDist = distances[node] + distance; // Relaxation Step if (newDist < distances[neighbor]) { distances[neighbor] = newDist; // Update the shortest distance to the neighbor previous[neighbor] = node; // Update the previous node pq.enqueue(neighbor, newDist); // Enqueue the neighbor with the updated distance } } } return { distances, previous }; } // Example usage const graph = { A: { B: 1, C: 4 }, B: { A: 1, C: 2, D: 5 }, C: { A: 4, B: 2, D: 1 }, D: { B: 5, C: 1 } }; const result = dijkstra(graph, 'A'); // start node 'A' console.log(result);
Reconstruct Path
// Simplified Queue using Sorting // Use Binary Heap (good) // or Binomial Heap (better) or Pairing Heap (best) class PriorityQueue { constructor() { this.queue = []; } enqueue(node, priority) { this.queue.push({ node, priority }); this.queue.sort((a, b) => a.priority - b.priority); } dequeue() { return this.queue.shift(); } isEmpty() { return this.queue.length === 0; } }
Initialize distances:
Process A:
Process B:
Process C:
Process D:
Comparing the time complexities of Dijkstra's algorithm with different priority queue implementations:
Priority Queue Type | Insert (M) | Extract Min | Decrease Key | Overall Time Complexity |
---|---|---|---|---|
Simple Array | O(1) | O(V) | O(V) | O(V^2) |
Binary Heap | O(log V) | O(log V) | O(log V) | O((V E) log V) |
Binomial Heap | O(log V) | O(log V) | O(log V) | O((V E) log V) |
Fibonacci Heap | O(1) | O(log V) | O(1) | O(V log V E) |
Pairing Heap | O(1) | O(log V) | O(log V) | O(V log V E) (practical) |
Dijkstra’s algorithm is a powerful and efficient method for finding shortest paths in graphs with non-negative weights. While it has limitations (e.g., cannot handle negative edge weights), it’s widely used in networking, routing, and other applications.
Here are some detailed resources where you can explore Dijkstra's algorithm along with rigorous proofs and examples:
Additionally, Wikipedia offers a great overview of the topic.
Citations:
[1] https://www.fuhuthu.com/CPSC420F2019/dijkstra.pdf
Feel free to share your thoughts or improvements in the comments!
The above is the detailed content of Understanding Dijkstras Algorithm: From Theory to Implementation. For more information, please follow other related articles on the PHP Chinese website!