codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

22 / 65 topics
22Dijkstra's Algorithm23Bellman-Ford Algorithm24Floyd-Warshall Algorithm
Tutorials/Data Structures & Algorithms/Dijkstra's Algorithm
🧮Data Structures & Algorithms

Dijkstra's Algorithm

Updated 2026-04-20
4 min read

Dijkstra's Algorithm

Dijkstra's Algorithm is a classic algorithm used to find the shortest path between nodes in a graph, which may represent, for example, road networks. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later. The algorithm efficiently computes the shortest paths from a single source vertex to all other vertices in a weighted graph where no edge has negative weight.

Overview

Dijkstra's Algorithm is particularly useful for graphs with non-negative weights, such as road networks where edges represent distances or travel times between locations. It operates by maintaining a set of unvisited nodes and iteratively selecting the node with the smallest tentative distance from the source node. The algorithm updates the distances to neighboring nodes if a shorter path is found.

Key Concepts

Graph Representation

A graph can be represented in several ways, but for Dijkstra's Algorithm, an adjacency list is commonly used due to its efficiency in terms of both space and time complexity. An adjacency list stores each vertex along with a list of adjacent vertices and their corresponding edge weights.

Priority Queue

Dijkstra's Algorithm uses a priority queue to efficiently select the node with the smallest tentative distance. A binary heap or Fibonacci heap can be used as the underlying data structure for the priority queue, providing efficient operations for insertion, deletion, and finding the minimum element.

Relaxation

Relaxation is the process of updating the shortest path estimate for a neighboring vertex. If a shorter path to a neighbor is found through the current node, the neighbor's distance is updated.

Algorithm Steps

  1. Initialization:

    • Set the distance to the source node as 0 and all other nodes as infinity.
    • Insert all nodes into the priority queue with their distances as keys.
  2. Main Loop:

    • While the priority queue is not empty, extract the node with the smallest distance (let's call it u).
    • For each neighbor v of u, calculate the tentative distance through u.
    • If this distance is less than the current known distance to v, update the distance and relax the edge.
  3. Termination:

    • The algorithm terminates when the priority queue is empty, meaning all nodes have been processed.

Pseudocode

import heapq

def dijkstra(graph, start):
    # Initialize distances
    distances = {node: float('infinity') for node in graph}
    distances[start] = 0
    
    # Priority queue to store (distance, node) pairs
    priority_queue = [(0, start)]
    
    while priority_queue:
        current_distance, current_node = heapq.heappop(priority_queue)
        
        # Nodes can get added to the priority queue multiple times. We only
        # process a vertex the first time we remove it from the priority queue.
        if current_distance > distances[current_node]:
            continue
        
        for neighbor, weight in graph[current_node].items():
            distance = current_distance + weight
            
            # Only consider this new path if it's better
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(priority_queue, (distance, neighbor))
    
    return distances

Real-World Example

Consider a simple road network with four cities: A, B, C, and D. The edges represent roads between the cities, and the weights represent the travel times in hours.

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}
}

start_node = 'A'
distances = dijkstra(graph, start_node)
print(distances)  # Output: {'A': 0, 'B': 1, 'C': 3, 'D': 4}

In this example, the shortest path from city A to all other cities is computed. City B is directly reachable in 1 hour, city C can be reached via city B in 3 hours, and city D can be reached via city C in 4 hours.

Best Practices

  • Use a Priority Queue: Always use a priority queue to efficiently select the node with the smallest tentative distance.
  • Handle Edge Cases: Ensure that the graph is connected and contains no negative weights. If the graph might contain negative weights, consider using Bellman-Ford's Algorithm instead.
  • Optimize Data Structures: Choose appropriate data structures for the adjacency list and priority queue to optimize performance.

Complexity Analysis

  • Time Complexity: O((V + E) log V), where V is the number of vertices and E is the number of edges. This complexity arises from the operations on the priority queue.
  • Space Complexity: O(V + E), for storing the graph and distances.

Conclusion

Dijkstra's Algorithm is a powerful tool for finding shortest paths in graphs with non-negative weights. Its efficiency and simplicity make it a popular choice in various applications, from network routing to pathfinding in video games. By understanding its principles and implementation details, you can effectively apply this algorithm to solve real-world problems involving shortest paths.

Further Reading

  • "Introduction to Algorithms" by Cormen, Leiserson, Rivest, and Stein
  • "Algorithms" by Robert Sedgewick and Kevin Wayne

By mastering Dijkstra's Algorithm, you'll be well-equipped to tackle a wide range of problems in graph theory and network analysis.


PreviousBreadth-First Search (BFS)Next Bellman-Ford Algorithm

Recommended Gear

Breadth-First Search (BFS)Bellman-Ford Algorithm