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.
What is Dijkstra's Algorithm?
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.
Input and Output
- Input: A graph G=(V,E) , where V is the set of vertices, E is the set of edges, and a source node s∈V .
- Output: The shortest path distances from s to all other nodes in V .
Core Concepts
- Relaxation: The process of updating the shortest known distance to a node.
- Priority Queue: Efficiently fetches the node with the smallest tentative distance.
- Greedy Approach: Processes nodes in non-decreasing order of their shortest distances.
The Algorithm
-
Initialize distances:
dist(s)=0,dist(v)=∞∀v=s Use a priority queue to store nodes based on their distances.
Repeatedly extract the node with the smallest distance and relax its neighbors.
Relaxation - Mathematical Explanation
- Initialization: dist(s)=0,dist(v)=∞for allv=s
where (s) is the source node, and (v) represents any other node.
-
Relaxation Step: for each edge
(u,v)
with weight
w(u,v)
:
If
dist(v)>dist(u) w(u,v)
, update:
dist(v)=dist(u) w(u,v),prev(v)=u
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.
Priority Queue - Mathematical Explanation
-
Queue Operation:
- The priority queue always dequeues the node
(u)
with the smallest tentative distance:
u=argv∈Qmindist(v)
- Why It Works: By processing the node with the smallest (dist(v)) , we guarantee the shortest path from the source to (u) .
- The priority queue always dequeues the node
(u)
with the smallest tentative distance:
Proof of Correctness
We prove the correctness of Dijkstra’s algorithm using strong induction.
What is 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.
Correctness of Dijkstra's Algorithm (Inductive Proof)
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.
JavaScript Implementation
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 (newDistReconstruct 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; } }Example Walkthrough
Graph Representation
- Nodes: A,B,C,D
-
Edges:
- A→B=(1),A→C=(4)
- B→C=(2),B→D=(5)
- C→D=(1)
Step-by-Step Execution
-
Initialize distances:
dist(A)=0,dist(B)=∞,dist(C)=∞,dist(D)=∞ -
Process A:
- Relax edges:
A→B,A→C.
dist(B)=1,dist(C)=4
- Relax edges:
A→B,A→C.
-
Process B:
- Relax edges:
B→C,B→D.
dist(C)=3,dist(D)=6
- Relax edges:
B→C,B→D.
-
Process C:
- Relax edge:
C→D.
dist(D)=4
- Relax edge:
C→D.
-
Process D:
- No further updates.
Final Distances and Path
Optimizations and Time Complexity
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) |
Key Points:
-
Simple Array:
- Inefficient for large graphs due to linear search for extract-min.
-
Binary Heap:
- Standard and commonly used due to its balance of simplicity and efficiency.
-
Binomial Heap:
- Slightly better theoretical guarantees but more complex to implement.
-
Fibonacci Heap:
- Best theoretical performance with ( O(1) ) amortized decrease-key, but harder to implement.
-
Pairing Heap:
- Simple and performs close to Fibonacci heap in practice.
Conclusion
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.
- Relaxation ensures shortest distances by iteratively updating paths.
- Priority Queue guarantees we always process the closest node, maintaining correctness.
- Correctness is proven via induction: Once a node's distance is finalized, it's guaranteed to be the shortest path.
Here are some detailed resources where you can explore Dijkstra's algorithm along with rigorous proofs and examples:
- Dijkstra's Algorithm PDF
- Shortest Path Algorithms on SlideShare
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!

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment
