Dijkstra’s Algorithm Demystified: A Complete Guide to Shortest Path Algorithms

Imagine you are travelling from one city to another. There may be several possible routes, but which route has the minimum distance? This is a common problem in computer science, and Dijkstra’s Algorithm provides an efficient way to solve it. Dijkstra’s algorithm is a graph algorithm used to find the shortest paths from a single source vertex to all other reachable vertices in a weighted graph. It is widely used in route planning, network routing, and other applications where minimizing distance or cost is important. It is one of the most commonly studied shortest path algorithms in Data Structures and Algorithms. In this blog, we will understand Dijkstra’s algorithm explained through a simple example, step-by-step execution, pseudocode, time complexity, and real-world applications.

Dijkstra’s Algorithm Explained_ Example, Steps & Time Complexity

What Is Dijkstra’s Algorithm?

Dijkstra’s algorithm is a greedy algorithm that finds the shortest path from a given source vertex to every other vertex in a weighted graph, provided all edge weights are non-negative.

A weighted graph is a graph in which each edge has an associated value called a weight. This weight may represent distance, cost, time, or another measurable quantity.

For example, in a road network:

  • Vertices represent cities.
  • Edges represent roads connecting cities.
  • Edge weights represent distances between cities.

Dijkstra’s algorithm determines the minimum total distance required to travel from a selected source city to other cities. This process is also known as Dijkstra’s shortest path algorithm in graph theory.

Why Is It Called a Greedy Algorithm?

A greedy algorithm makes the best available choice at each step, hoping to build an optimal solution.

Dijkstra’s algorithm follows this strategy by repeatedly selecting the unvisited vertex with the smallest known distance from the source.

Once a vertex with the smallest tentative distance is selected, its shortest distance is finalized, provided all edge weights are non-negative.

The algorithm then checks whether travelling through that vertex can produce shorter paths to its neighboring vertices. This approach demonstrates how a greedy algorithm in data structures works when solving a shortest-path problem.

registor_now_P

Step-by-Step Execution of Dijkstra’s Algorithm

Consider the following weighted undirected graph.

For reference, the edges of this graph (as used in the steps below) are:

EdgeWeight
A – B4
A – C1
C – B2
C – D5
B – D1
B – E7
D – E3

Our objective is to find the shortest distance from source vertex A to every other vertex using Dijkstra’s algorithm step by step.

Step 1: Initialization

Initially assign a distance of 0 to the source vertex A and infinity to all other vertices because their shortest distances are not yet known.

VertexDistance from A
A0
B∞
C∞
D∞
E∞

Step 2: Select vertex A

A has the smallest distance, which is 0.

Its neighbors are B and C.

  • Distance to B = 0 + 4 = 4
  • Distance to C = 0 + 1 = 1

Mark A as visited.

VertexDistance from A
A0
B4
C1
D∞
E∞

Step 3: Select vertex C

Among the unvisited vertices, C has the smallest distance of 1.

Check its neighbors:

  • Through C, distance to B = 1 + 2 = 3. This is shorter than 4, so update B to 3.
  • Through C, distance to D = 1 + 5 = 6. Update D to 6.

Mark C as visited.

VertexDistance from A
A0
B3
C1
D6
E∞

Step 4: Select vertex B

B has the smallest unvisited distance of 3.

Check its neighbors and update the distances:

  • Through B, distance to D = 3 + 1 = 4. This is shorter than 6, so update D to 4.
  • Through B, distance to E = 3 + 7 = 10. Update E to 10.

Mark B as visited.

VertexDistance from A
A0
B3
C1
D4
E10

Step 5: Select vertex D

D has the smallest unvisited distance of 4.

Check its neighbor E:

  • Through D, distance to E = 4 + 3 = 7.
  • The previous distance to E was 10, so update it to 7.

Mark D as visited.

VertexDistance from A
A0
B3
C1
D4
E7

Step 6: Select vertex E

E is the remaining unvisited vertex, with distance 7.

Mark E as visited. The algorithm is complete as all vertices have been covered.

VertexDistance from A
A0
B3
C1
D4
E7

Final Shortest Distances

The following table shows the final result of finding the shortest path using Dijkstra’s algorithm.

DestinationShortest path from ATotal distance
AA0
BA → C → B3
CA → C1
DA → C → B → D4
EA → C → B → D → E7
Notice that the direct path from A to B has a cost of 4. However, travelling through C gives a total cost of 1 + 2 = 3, which is shorter. This demonstrates why checking alternative paths is essential in a shortest path algorithm in a weighted graph.

Pseudocode for Dijkstra’s Algorithm

The following Dijkstra’s algorithm pseudocode explains the basic steps involved in finding the shortest distances from a source vertex.

Dijkstra(Graph, source)

1. Set the source vertex distance to 0.
2. Set all other vertex distances to INF.
3. Mark all vertices as unvisited.
4. Repeat until no unvisited vertex with a finite distance remains:
     a. Select the unvisited vertex u with the smallest distance.
     b. If no reachable unvisited vertex exists, stop.
     c. Mark u as visited.
     d. For each unvisited neighbor v of u:
          If distance[u] + weight(u, v) < distance[v], update:
               distance[v] = distance[u] + weight(u, v)
5. Return the distance[] array.

This pseudocode illustrates the fundamental Dijkstra’s algorithm implementation logic used in graph-based shortest-path problems.

Time Complexity of Dijkstra’s Algorithm

The Dijkstra’s algorithm time complexity depends on the data structures used to implement the algorithm.

a. Using an adjacency matrix

When the algorithm searches all vertices to find the smallest unvisited distance, the time complexity is:

O(V2)

Here, V represents the number of vertices.

b. Using an adjacency list and a binary min-heap

A priority queue helps select the vertex with the smallest tentative distance efficiently.

The typical time complexity is:

O((V + E) log V)

Here:

  • V = number of vertices
  • E = number of edges

For dense graphs or small graphs, an adjacency matrix may be a convenient implementation. For sparse graphs, an adjacency list with a min-heap is often more efficient.

Understanding these complexities is important when comparing different shortest path algorithms in data structures, particularly when working with large graphs.

 

Explore Courses - Learn More

 

Applications of Dijkstra’s Algorithm

Dijkstra’s algorithm has several practical applications. These Dijkstra’s algorithm applications demonstrate how shortest-path calculations are used in real-world systems.

1. GPS and route planning

Navigation systems can use shortest-path algorithms to determine routes based on distance or travel cost. Real navigation systems may use additional techniques and changing traffic information.

2. Computer networks

Routing protocols such as OSPF use Dijkstra’s shortest-path algorithm to calculate shortest-path trees from a router.

3. Robotics

Robots can use shortest-path techniques to find routes through a map or grid, where edge weights represent movement costs.

4. Transportation systems

The algorithm can help determine low-cost routes through networks of roads, railway connections, or other transport links.

5. Game development

Games can use shortest-path algorithms to help characters navigate maps and reach destinations.

Limitations of Dijkstra’s Algorithm

Although Dijkstra’s algorithm is useful, it has some limitations:

  • It assumes that edge weights are non-negative.
  • It does not correctly solve the general shortest-path problem when negative-weight edges are present.
  • A disconnected graph may contain vertices that cannot be reached from the source.
  • A simple adjacency-matrix implementation may be inefficient for very large, sparse graphs.
  • When negative edge weights must be supported, the Bellman–Ford algorithm is a common alternative.

This is an important consideration when understanding Dijkstra’s algorithm vs Bellman-Ford, as both algorithms solve shortest-path problems but have different capabilities.

Dijkstra’s algorithm starts by assigning a distance of 0 to the source vertex and infinity to all other vertices. It then selects the unvisited vertex with the smallest distance, updates the distances of its neighboring vertices, and marks the selected vertex as visited. This process continues until all reachable vertices have been processed.

Practice Question

Consider a weighted graph with vertices A, B, C, and D, and edges:

Consider A as the source vertex, calculate the shortest distance to each vertex. Show the tentative distances after every iteration and identify the final shortest paths.

This practice question helps learners understand how to find the shortest path using Dijkstra’s algorithm and apply the algorithm to a different weighted graph.

Conclusion

Dijkstra’s algorithm is an important graph algorithm that demonstrates how a greedy strategy can solve a shortest-path problem.

By repeatedly selecting the unvisited vertex with the smallest tentative distance and relaxing its neighboring edges, the algorithm determines the shortest distances from a source to all reachable vertices.

Understanding this algorithm builds a strong foundation for studying graph traversal, greedy algorithms, network routing, and other advanced Data Structures and Algorithms topics.

Dijkstra’s algorithm finds shortest paths in weighted directed and undirected graphs with non-negative edge weights by making the best available distance choice at each step.

Learning Dijkstra’s shortest path algorithm, its implementation, time complexity, and practical applications provides a strong foundation for understanding graph algorithms and solving advanced programming problems.

 

Talk to Academic Advisor

Frequently Asked Questions

Dijkstra’s algorithm is a greedy graph algorithm used to find the shortest path from a single source vertex to all other reachable vertices in a weighted graph. Its main purpose is to calculate the minimum distance or cost between vertices when all edge weights are non-negative.

Dijkstra’s algorithm is called a greedy algorithm because it repeatedly selects the unvisited vertex with the smallest tentative distance from the source. It makes the best available choice at each step and updates the distances of neighboring vertices to find the shortest paths.

Dijkstra’s algorithm starts by assigning a distance of 0 to the source vertex and infinity to all other vertices. It then selects the unvisited vertex with the smallest distance, updates the distances of its neighboring vertices, and marks the selected vertex as visited. This process continues until all reachable vertices have been processed.

To find the shortest path using Dijkstra’s algorithm, first select a source vertex and initialize its distance to 0. Assign infinity to all other vertices. Then repeatedly select the unvisited vertex with the smallest tentative distance and calculate the distances to its neighbors. For example, if the edges A–B, A–C, and C–B have weights 4, 1, and 2 respectively, the direct distance from A to B is 4. However, travelling through C gives a total distance of 1 + 2 = 3. Therefore, the shortest path from A to B is A → C → B, with a total distance of 3.

The source vertex is the starting point from which the shortest distances to all other reachable vertices are calculated. Its initial distance is set to 0, while the distances of all other vertices are initialized to infinity.

If a vertex cannot be reached from the source vertex, its distance remains infinity because no valid path exists between them. Dijkstra’s algorithm processes only the vertices that are reachable from the selected source.

Author

Embedded Systems and IOT Trainer– IIES

Updated On: 30-10-26


10+ years of hands-on experience delivering practical training in Embedded Systems and it's design