1. Home
  2. Explore
  3. Computer Science
  4. Dijkstra's Shortest Path Algorithm

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Dijkstra's Shortest Path Algorithm

🗺️ Shortest Path Algorithms: Dijkstra and DAGs

This document provides a comprehensive overview of shortest path algorithms, focusing on the concepts of relaxation, algorithms for Directed Acyclic Graphs (DAGs), and Dijkstra's algorithm for graphs with non-negative edges.


🔁 The Relaxation Operation

The relaxation operation is a fundamental process in all shortest path algorithms. It involves updating the estimated shortest path distance to a vertex if a shorter path is discovered.

🎯 Key Concepts

  • d(v): Represents the current estimated length of the shortest path from the source s to vertex v.

  • d(s): Initialized to 0 for the source vertex, as the path from s to s has zero length.

  • d(v) for v ≠ s: Initially set to infinity, indicating that no path is currently known.

  • δ(s, v): Denotes the actual shortest path length from s to v. The goal of any shortest path algorithm is to converge d(v) to δ(s, v).

  • π(v): Represents the predecessor of vertex v in the current shortest path from s to v. This is crucial for reconstructing the path once the algorithm completes.

📝 Formal Definition of Relaxation

The relaxation step for an edge (u, v) with weight w(u, v) is defined as follows:

If d(v) > d(u) + w(u, v): - d(v) ← d(u) + w(u, v) - π(v) ← u

This means if a path from s to u with length d(u), followed by the edge (u, v) with weight w(u, v), offers a shorter path to v than its current d(v) value, then d(v) is updated, and u becomes the new predecessor of v.

🛡️ Safety of Relaxation

A critical property of the relaxation operation is its safety or correctness. This means that d(v) will never be updated to a value less than the true shortest path δ(s, v). In other words, d(v) ≥ δ(s, v) for all vertices v at any point during the algorithm's execution.

💡 Proof Intuition (by Induction)

  1. Inductive Hypothesis: Assume that d(u) ≥ δ(s, u) holds for the vertex u before relaxing an edge (u, v).

  2. Triangle Inequality: The shortest path from s to v, δ(s, v), must be less than or equal to the shortest path from s to u plus the shortest path from u to v.

    δ(s,v)≤δ(s,u)+δ(u,v)\delta(s, v) \le \delta(s, u) + \delta(u, v)δ(s,v)≤δ(s,u)+δ(u,v)
  3. Since w(u, v) is the direct edge weight from u to v, it must be greater than or equal to the shortest path from u to v (δ(u, v)), i.e., w(u, v) ≥ δ(u, v).

  4. Combining these, we get:

    δ(s,v)≤δ(s,u)+w(u,v)\delta(s, v) \le \delta(s, u) + w(u, v)δ(s,v)≤δ(s,u)+w(u,v)
  5. By the inductive hypothesis, δ(s, u) ≤ d(u). Substituting this:

    δ(s,v)≤d(u)+w(u,v)\delta(s, v) \le d(u) + w(u, v)δ(s,v)≤d(u)+w(u,v)
  6. When the relaxation step occurs, d(v) is updated to d(u) + w(u, v). Therefore, the new d(v) value will always be greater than or equal to δ(s, v).

    δ(s,v)≤d(v)new\delta(s, v) \le d(v)_{\text{new}}δ(s,v)≤d(v)new​

This lemma ensures that any algorithm solely relying on relaxation to update d values will maintain correctness, always converging downwards towards the true shortest path values without undershooting.


🌳 Shortest Paths in Directed Acyclic Graphs (DAGs)

For Directed Acyclic Graphs (DAGs), finding shortest paths is simplified because there are no cycles, which eliminates the problem of negative cycles that can lead to indeterminate shortest path values (approaching negative infinity). DAGs can have negative edge weights.

⚙️ Algorithm for DAGs

The algorithm leverages the unique structure of DAGs:

  1. Topological Sort: Perform a topological sort of the DAG. This produces a linear ordering of vertices such that for every directed edge (u, v), u appears before v in the ordering.

    • Topological sort typically uses a Depth-First Search (DFS) and takes O(V + E) time.

  2. Single Pass Relaxation: Iterate through the vertices in the topologically sorted order from left to right. For each vertex u in this order, relax all outgoing edges (u, v).

    • Initialize d(s) = 0 for the source s and d(v) = ∞ for all other vertices.

    • Process each vertex u only once.

    • Relax each outgoing edge (u, v) once.

⏱️ Complexity

The total time complexity for finding shortest paths in a DAG is O(V + E).

  • Topological sort: O(V + E)

  • Relaxation pass: O(V) (for iterating through vertices) + O(E) (for relaxing each edge once).

➕ Advantages

  • Works correctly even with negative edge weights, as long as there are no cycles.

  • Simple and efficient, achieving linear time complexity.

  • An excellent example of dynamic programming, where subproblems (shortest paths to earlier vertices in the topological sort) are solved before superproblems.

⚠️ Important Distinction

This algorithm is not subsumed by Dijkstra's algorithm. Dijkstra's algorithm requires non-negative edge weights but handles cycles. The DAG algorithm handles negative edges but cannot handle cycles.


🌐 Dijkstra's Algorithm

Dijkstra's algorithm finds the shortest paths from a single source vertex to all other vertices in a graph where all edge weights are non-negative (w(u, v) ≥ 0). It is a greedy algorithm that iteratively builds the set of vertices for which the shortest path has been definitively found.

🧪 Pseudocode

Dijkstra(G, W, s):
  Initialize-Single-Source(G, s) // sets d(s) = 0, d(v) = ∞ for v ≠ s, π(v) = NIL
  S = ∅                      // S: set of vertices whose final shortest-path weights have been determined
  Q = G.V                    // Q: min-priority queue of vertices, keyed by their d values

  while Q is not empty:
    u = Extract-Min(Q)       // Extract vertex with the smallest d value from Q
    S = S ∪ {u}              // Add u to the set of processed vertices
    for each vertex v in Adj[u]: // For each neighbor v of u
      Relax(u, v, W)         // Update d(v) if a shorter path through u is found

🧠 Intuition (The "Gravity" Demo)

Imagine the source vertex is held up, and all other vertices are connected by strings (edges) whose lengths correspond to edge weights. When the source is lifted, the vertices that are "closest" (shortest path) will be pulled up first, becoming taut. This physical analogy demonstrates the greedy nature of Dijkstra: it always selects the unprocessed vertex with the smallest current shortest path estimate.

🚶 Step-by-Step Execution

  1. Initialization:

    • d(s) = 0, d(v) = ∞ for all v ≠ s.

    • S (set of finalized vertices) is empty.

    • Q (priority queue) contains all vertices, keyed by their d values.

  2. First Iteration:

    • Extract-Min(Q) will always return s (since d(s) = 0 and all others are ∞).

    • s is added to S.

    • All edges emanating from s are relaxed, updating d values for its neighbors and potentially changing their priorities in Q.

  3. Subsequent Iterations:

    • Extract-Min(Q) always selects the vertex u from Q that has the smallest d(u) value. This d(u) is guaranteed to be its final shortest path distance δ(s, u).

    • u is moved from Q to S.

    • All edges leaving u are relaxed. This might decrease d values for u's neighbors, requiring updates in the priority queue.

  4. The algorithm continues until Q is empty, at which point S contains all vertices with their final shortest path distances.

⏱️ Complexity Analysis

The efficiency of Dijkstra's algorithm heavily depends on the priority queue implementation.

Operation

d(v) initialization

Extract-Min

Decrease-Key (Relaxation)

Number of calls

O(V)

O(V)

O(E)

📉 Priority Queue Implementations

  1. Array (Simple List):

    • Extract-Min: O(V) (linear scan to find minimum).

    • Decrease-Key: O(1) (direct access and update).

    • Total Complexity: O(V \cdot V + E \cdot 1) = O(V^2 + E) = O(V^2) (since E can be up to V^2).

    • Best for dense graphs (where E is close to V^2).

  2. Binary Min-Heap:

    • Extract-Min: O(log V) (remove root, heapify).

    • Decrease-Key: O(log V) (update value, bubble up).

    • Total Complexity: O(V log V + E log V) = O((V + E) log V).

    • Generally better for sparse graphs (where E is much smaller than V^2).

  3. Fibonacci Heap (Advanced data structure, not typically covered in introductory courses):

    • Extract-Min: O(log V) (amortized).

    • Decrease-Key: O(1) (amortized).

    • Total Complexity: O(V log V + E).

    • This is the theoretically most efficient implementation for Dijkstra's algorithm.

🚫 Limitations

  • Cannot handle negative edge weights. If a negative edge exists, Dijkstra's algorithm may produce incorrect results because its greedy choice (assuming the shortest path to u is final) might be invalidated by a later path involving a negative edge. For graphs with negative edges (but no negative cycles), the Bellman-Ford algorithm is used.


Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent