Skip to main content
Algorithms Analysis
CHAPTER 26 Beginner

Shortest Path Algorithms (Dijkstra)

Updated: May 17, 2026
15 min read

# CHAPTER 26

Shortest Path Algorithms (Dijkstra)

1. Introduction

In Chapter 23, we used Breadth-First Search (BFS) to find the shortest path on an unweighted grid by counting the physical number of jumps. But the real world does not work like that. If Path A requires 1 jump across a massive 500-mile desert, and Path B requires 3 small jumps on high-speed highways totaling 20 miles, BFS will fatally choose Path A! To calculate navigation on a Weighted Graph, computer scientist Edsger W. Dijkstra invented a revolutionary algorithm in 1956. Dijkstra’s Algorithm tracks the cumulative weight (distance/cost) of traversing edges, completely changing the way the world calculates logistics, mapping, and routing.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain the cumulative distance tracking mechanism.
  • Understand the integration of the Min-Heap Priority Queue.
  • Trace the aggressive "Relaxation" of geometric paths.
  • Analyze the $O(E \log V)$ Time Complexity.
  • Identify the fatal flaw regarding Negative Edge Weights.

3. The Execution Logic

Dijkstra's is a Greedy Algorithm. It maintains an array of calculated distances from the Start Node to every other Node. It starts with the distances set to Infinity, and actively tries to lower them!

The Core Mechanisms:

  1. 1. The Distance Array: Create an array tracking the shortest known distance to every node. Initialize the Start Node to 0, and all others to Infinity.
  1. 2. The Priority Queue (Min-Heap): Just like Prim's algorithm, Dijkstra throws pathways into a Min-Heap so it can aggressively extract the absolute cheapest, shortest available path.
  1. 3. The Relaxation Process: When Dijkstra extracts a Node, it evaluates all of its outgoing neighbors. It calculates: *(Distance to Current Node) + (Weight of Edge to Neighbor)*.
  • If this new cumulative total is less than the currently known Infinity (or previously recorded distance) to that Neighbor, we physically overwrite the array with the new lower number! We have "Relaxed" the path.

4. Visualizing the Traversal

Imagine finding the shortest path from A to C. Edges: A->B (Weight 5), B->C (Weight 2), A->C (Weight 10).
  1. 1. Start at A. Distance Array: [A:0, B:∞, C:∞].
  1. 2. Evaluate A's neighbors (B and C).
  • Path A->B: 0 + 5 = 5. Is 5 < ∞? Yes! Update B to 5.
  • Path A->C: 0 + 10 = 10. Is 10 < ∞? Yes! Update C to 10.
  • Array is now: [A:0, B:5, C:10].
  1. 3. Greedy Move! The Min-Heap extracts the absolute smallest available node (B).
  1. 4. Evaluate B's neighbors (C).
  • Path B->C: Current Distance to B (5) + Weight of B->C (2) = 7.
  • Is 7 < 10? YES! We found a faster backdoor route! We overwrite the old data.
  • Final Array: [A:0, B:5, C:7].

5. Implementation in Code

java
123456789101112131415161718192021222324252627282930313233343536373839404142434445
// Java Example: Dijkstra's Algorithm
import java.util.*;

public class Dijkstra {
    
    // A helper class to store Node and Distance in the Queue
    static class Node implements Comparable<Node> {
        int vertex, weight;
        Node(int v, int w) { vertex = v; weight = w; }
        public int compareTo(Node n) { return Integer.compare(this.weight, n.weight); }
    }

    public void calculateShortestPath(int start, List<List<Node>> adjList, int V) {
        // 1. Initialize Distance Array to Infinity
        int[] dist = new int[V];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[start] = 0; // Distance to itself is 0
        
        // 2. Initialize Min-Heap Priority Queue
        PriorityQueue<Node> pq = new PriorityQueue<>();
        pq.add(new Node(start, 0));
        
        // 3. Execution Engine
        while (!pq.isEmpty()) {
            // Extract the closest geometric node!
            Node current = pq.poll();
            
            // 4. Evaluate Neighbors
            for (Node neighbor : adjList.get(current.vertex)) {
                
                // The mathematical "Relaxation" evaluation!
                int newDist = dist[current.vertex] + neighbor.weight;
                
                // If the new cumulative distance is structurally cheaper...
                if (newDist < dist[neighbor.vertex]) {
                    
                    dist[neighbor.vertex] = newDist; // Overwrite the old record!
                    pq.add(new Node(neighbor.vertex, newDist)); // Throw into Queue!
                }
            }
        }
        
        // At completion, the 'dist' array holds the absolute fastest route to ALL nodes!
    }
}

6. Complexity Analysis

Because Dijkstra utilizes the exact same Min-Heap architecture as Prim's algorithm, their complexities are remarkably similar.
MetricComplexityDescription
Time Complexity$O(E \log V)$The algorithm must traverse all Edges ($E$) and execute $O(\log V)$ insertions/extractions into the Priority Queue.
Space Complexity$O(V + E)$Must allocate the Distance array, alongside the graph representation in RAM.

7. The Catastrophic Weakness: Negative Weights

Dijkstra's is a Greedy Algorithm. It assumes that every time you traverse an Edge, your cumulative distance MUST go up (because distances in the real world are positive).

What if a mathematical graph contains an Edge with a Weight of -50? Dijkstra's logic violently shatters. It extracts a node, falsely believes it has found the shortest localized path, locks it, and completely ignores the massive -50 backdoor shortcut hidden deeper in the graph! *Rule: Dijkstra mathematically CANNOT process graphs containing Negative Edge Weights.*

8. Real-World Applications

  1. 1. Google Maps / Waze Navigation: Dijkstra calculates the absolute fastest physical driving route by mapping intersections as Vertices, roads as Edges, and traffic delays as Weights.
  1. 2. OSPF Routing Protocol: Internet infrastructure routers actively use Dijkstra to map the global topology of data centers, calculating the lowest-latency fiber-optic paths to bounce data packets.

9. Common Mistakes

  • Forgetting the Priority Queue: If a junior developer tries to write Dijkstra using a standard array to find the minimum node, the algorithm degrades from a lightning-fast $O(E \log V)$ to a catastrophic $O(V^2)$, violently crashing on large graphs. You must explicitly use a Min-Heap.

10. Exercises

  1. 1. If a Graph has a pathway A->B (Weight 10) and B->C (Weight -20), trace why Dijkstra's algorithm might finalize C with an incorrect higher distance.
  1. 2. What is the fundamental difference in the Relaxation logic between Dijkstra's algorithm and Prim's algorithm? *(Hint: Look at the cumulative addition).*

11. MCQs with Answers

Question 1

What severe architectural limitation of Breadth-First Search (BFS) explicitly mandated the invention of Dijkstra's Algorithm?

Question 2

During initialization, what specific value is heavily assigned to all unvisited destination nodes within the overarching Distance Array?

Question 3

When Dijkstra's algorithmic engine discovers a secondary, alternative pathway to a Node that is mathematically cheaper than the previously recorded route, what is this specific overwriting process called?

Question 4

To mathematically guarantee the $O(E \log V)$ execution speeds required for massive global systems, what highly specialized Data Structure must orchestrate the extraction sequence?

Question 5

Because Dijkstra is fundamentally classified as a Greedy Algorithm, what anomalous geometric condition will cause the entire logic matrix to catastrophically fail?

Question 6

What happens if an architect attempts to run Dijkstra's Algorithm on a standard, Unweighted Graph?

Question 7

When evaluating the explicit Java algorithmic code int newDist = dist[current.vertex] + neighbor.weight;, what is the system physically calculating?

Question 8

What differentiates the structural architecture of Dijkstra's Priority Queue from Prim's MST Priority Queue?

Question 9

If a multi-billion dollar internet provider is mapping optimal routing tables (OSPF) across thousands of global data servers, why is Dijkstra heavily favored?

Q10. True or False: If a Graph contains a mathematical cycle, Dijkstra's Algorithm will become permanently trapped in an infinite execution loop. a) True. The algorithm will loop around the cycle endlessly. b) False. Because the mathematical "Relaxation" condition strictly mandates that the new path must be explicitly LESS than the known path, encountering an inflating cycle repeatedly will trigger False, instantly breaking the execution chain. Answer: b) False. Because the mathematical "Relaxation" condition strictly mandates that the new path...

12. Interview Preparation

Top Interview Questions:
  • *System Modification:* "Dijkstra calculates the distance, but how do I physically print the actual path (e.g., A -> B -> C)?" *(Answer: Maintain a PreviousNode array alongside the Distance array! Every time you successfully execute a 'Relaxation', explicitly record Prev[neighbor] = current. When the algorithm finishes, start at the Destination and trace the Prev array backwards to the Start!)*

13. Summary

Dijkstra's Algorithm is the definitive standard for calculating traversal mechanics across positive Weighted Graphs. By fusing the aggressive expansion of Graph Theory with the hyper-efficient extraction speeds of the Min-Heap Priority Queue, it evaluates millions of paths in milliseconds. However, its fatal vulnerability to negative weights remains unresolved.

14. Next Chapter Recommendation

What if your graph is mapping the Stock Market? What if traversing a path actually *makes* you money, representing a Negative Weight constraint? Dijkstra will violently crash. We must abandon Greedy logic entirely and look to the safety of overlapping iterations. In Chapter 27: Shortest Path Algorithms (Bellman-Ford), we will solve the negative paradox.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·