国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial Understanding Dijkstra&#s Algorithm: From Theory to Implementation

Understanding Dijkstra&#s Algorithm: From Theory to Implementation

Dec 14, 2024 am 03:18 AM

Understanding Dijkstra

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)G = (V, E) G=(V,E) , where VV V is the set of vertices, EE E is the set of edges, and a source node sVs in V s∈V .
  • Output: The shortest path distances from ss s to all other nodes in VV V .

Core Concepts

  1. Relaxation: The process of updating the shortest known distance to a node.
  2. Priority Queue: Efficiently fetches the node with the smallest tentative distance.
  3. Greedy Approach: Processes nodes in non-decreasing order of their shortest distances.

The Algorithm

  1. Initialize distances:

    dist(s)=0,dist(v)=???vs text{dist}(s) = 0, text{dist}(v) = infty ; quad forall v neq s dist(s)=0,dist(v)=∞?v=s
  2. Use a priority queue to store nodes based on their distances.

  3. Repeatedly extract the node with the smallest distance and relax its neighbors.

Relaxation - Mathematical Explanation

  • Initialization: dist(s)=0,dist(v)=?for?all?vstext{dist}(s) = 0, text{dist}(v) = infty , text{for all} , v neq s dist(s)=0,dist(v)=for?allv=s

where (s)( s ) (s) is the source node, and (v)( v ) (v) represents any other node.

  • Relaxation Step: for each edge (u,v)(u, v) (u,v) with weight w(u,v)w(u, v) w(u,v) : If dist(v)>dist(u) w(u,v)text{dist}(v) > text{dist}(u) w(u, v) dist(v)>dist(u) w(u,v) , update:
    dist(v)=dist(u) w(u,v),prev(v)=utext{dist}(v) = text{dist}(u) w(u, v), quad text{prev}(v) = u 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)( u ) (u) with the smallest tentative distance:
      u=arg?min?vQdist(v)u = arg min_{v in Q} text{dist}(v) u=argv∈Qmin?dist(v)
    • Why It Works: By processing the node with the smallest (dist(v))( text{dist}(v) ) (dist(v)) , we guarantee the shortest path from the source to (u)( u ) (u) .

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))( P(n) ) (P(n)) , we assume the truth of (P(1),P(2),,P(k))( P(1), P(2), dots, P(k) ) (P(1),P(2),…,P(k)) to prove (P(k 1))( P(k 1) ) (P(k 1)) . This differs from regular induction, which assumes only (P(k))( P(k) ) (P(k)) to prove (P(k 1))( P(k 1) ) (P(k 1)) . Explore it in greater detail in my other post.

Correctness of Dijkstra's Algorithm (Inductive Proof)

  1. Base Case:

    The source node (s)( s ) (s) is initialized with dist(s)=0text{dist}(s) = 0 dist(s)=0 , which is correct.

  2. Inductive Hypothesis:

    Assume all nodes processed so far have the correct shortest path distances.

  3. Inductive Step:

    The next node (u)( u ) (u) is dequeued from the priority queue. Since dist(u)text{dist}(u) dist(u) is the smallest remaining distance, and all previous nodes have correct distances, dist(u)text{dist}(u) 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 (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;
  }
}

Example Walkthrough

Graph Representation

  • Nodes: A,B,C,DA, B, C, D A,B,C,D
  • Edges:
    • AB=(1),AC=(4)A to B = (1), A to C = (4) A→B=(1),A→C=(4)
    • BC=(2),BD=(5)B to C = (2), B to D = (5) B→C=(2),B→D=(5)
    • CD=(1)C to D = (1) C→D=(1)

Step-by-Step Execution

  1. Initialize distances:

    dist(A)=0,??dist(B)=,??dist(C)=,??dist(D)= text{dist}(A) = 0, ; text{dist}(B) = infty, ; text{dist}(C) = infty, ; text{dist}(D) = infty dist(A)=0,dist(B)=∞,dist(C)=∞,dist(D)=
  2. Process A:

    • Relax edges: AB,AC.A to B, A to C. A→B,A→C.
      dist(B)=1,??dist(C)=4text{dist}(B) = 1, ; text{dist}(C) = 4 dist(B)=1,dist(C)=4
  3. Process B:

    • Relax edges: BC,BD.B to C, B to D. B→C,B→D.
      dist(C)=3,??dist(D)=6text{dist}(C) = 3, ; text{dist}(D) = 6 dist(C)=3,dist(D)=6
  4. Process C:

    • Relax edge: CD.C to D. C→D.
      dist(D)=4text{dist}(D) = 4 dist(D)=4
  5. Process D:

    • No further updates.

Final Distances and Path

dist(A)=0,??dist(B)=1,??dist(C)=3,??dist(D)=4 text{dist}(A) = 0, ; text{dist}(B) = 1, ; text{dist}(C) = 3, ; text{dist}(D) = 4 dist(A)=0,dist(B)=1,dist(C)=3,dist(D)=4

ABCD A to B to C to D A→B→C→D

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:

  1. Simple Array:
    • Inefficient for large graphs due to linear search for extract-min.
  2. Binary Heap:
    • Standard and commonly used due to its balance of simplicity and efficiency.
  3. Binomial Heap:
    • Slightly better theoretical guarantees but more complex to implement.
  4. Fibonacci Heap:
    • Best theoretical performance with ( O(1) ) amortized decrease-key, but harder to implement.
  5. 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 Dijkstra&#s Algorithm: From Theory to Implementation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

See all articles