Understanding Dijkstra's Algorithm for Shortest Path Finding

In this article, we will explore Dijkstra's Algorithm, a powerful method for finding the shortest path in a graph. We'll break down the algorithm step-by-step and illustrate its application with practical examples.
Written by
Jamie

What is Dijkstra’s Algorithm?

Dijkstra’s Algorithm is a graph search algorithm that solves the shortest path problem for a graph with non-negative edge weights. It efficiently finds the shortest path from a starting node to all other nodes in the graph.

How Dijkstra’s Algorithm Works

  1. Initialization: Start with a graph represented as a set of nodes (vertices) connected by edges with weights (distances).
  2. Set Distances: Assign an initial distance of 0 to the starting node and infinity to all other nodes.
  3. Visit Nodes: Use a priority queue to visit nodes in order of their distance, updating the distances of neighboring nodes.
  4. Update Distances: For each neighboring node, if the calculated distance through the current node is less than the known distance, update it.
  5. Repeat: Continue visiting nodes until all nodes have been processed.

Example Graph

Consider the following weighted graph:

    A
   / \
  1   4
 /     \
B---2---C
 \     /
  3   5
   \ /
    D

Graph Representation:

  • Nodes: A, B, C, D
  • Edges with weights:
    • A to B: 1
    • A to C: 4
    • B to C: 2
    • B to D: 3
    • C to D: 5

Step-by-Step Application of Dijkstra’s Algorithm

  1. Initialization:

    • Start Node: A
    • Distances: A=0, B=∞, C=∞, D=∞
    • Priority Queue: [(0, A)]
  2. Visit A:

    • Update distances for B and C:
      • B: min(∞, 0 + 1) = 1
      • C: min(∞, 0 + 4) = 4
    • New Distances: A=0, B=1, C=4, D=∞
    • Priority Queue: [(1, B), (4, C)]
  3. Visit B:

    • Update distances for C and D:
      • C: min(4, 1 + 2) = 3
      • D: min(∞, 1 + 3) = 4
    • New Distances: A=0, B=1, C=3, D=4
    • Priority Queue: [(3, C), (4, D)]
  4. Visit C:

    • Update distance for D:
      • D: min(4, 3 + 5) = 4 (no change)
    • New Distances: A=0, B=1, C=3, D=4
    • Priority Queue: [(4, D)]
  5. Visit D:

    • All nodes visited.

Final Shortest Path Distances from A

  • A to A: 0
  • A to B: 1
  • A to C: 3
  • A to D: 4

Conclusion

Dijkstra’s Algorithm efficiently finds the shortest paths from a starting node to all other nodes in a graph. By following the steps outlined above, you can apply this algorithm to a variety of problems in graph theory, such as mapping routes or optimizing network paths.

Explore More Graph Theory Problem Solving

Discover more examples and insights in this category.

View All Graph Theory Problem Solving