DEV Community

Cover image for Understanding Dijkstra's Algorithm: A Step-by-Step Guide πŸš€
Dipak Ahirav
Dipak Ahirav

Posted on

Understanding Dijkstra's Algorithm: A Step-by-Step Guide πŸš€

Dijkstra's Algorithm is one of the most famous algorithms in computer science and graph theory, used to find the shortest path from a starting node to all other nodes in a weighted graph. In this blog, we will delve deep into the workings of Dijkstra's Algorithm, providing a step-by-step guide with examples and code implementations. πŸ“

please subscribe to my YouTube channel to support my channel and get more web development tutorials.

What is Dijkstra's Algorithm? πŸ€”

Dijkstra's Algorithm, named after its creator Edsger W. Dijkstra, is used to solve the shortest path problem for a graph with non-negative edge weights. It finds the shortest path from a source vertex to all other vertices in the graph.

How Does Dijkstra's Algorithm Work? πŸ› οΈ

The algorithm works by iteratively selecting the vertex with the smallest known distance from the source and updating the distances of its neighboring vertices. Here’s a step-by-step explanation:

  1. Initialization:

    • Set the distance to the source node to zero and to all other nodes to infinity.
    • Mark all nodes as unvisited. Create a set of all the unvisited nodes called the unvisited set.
    • Set the initial node as the current node.
  2. Visit Neighboring Nodes:

    • For the current node, consider all its unvisited neighbors and calculate their tentative distances through the current node. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has a length of 2, then the distance to B through A will be 6 + 2 = 8. If B was previously marked with a distance greater than 8 then change it to 8. If the neighboring node has already been visited, skip it.
  3. Mark the Current Node as Visited:

    • Once all neighbors of the current node have been visited, mark the current node as visited. A visited node will not be checked again.
  4. Select the Next Current Node:

    • Select the unvisited node with the smallest tentative distance and set it as the new "current node", then go back to step 2.
  5. Repeat:

    • Repeat steps 2-4 until all nodes have been visited. By then, the shortest path to all nodes will have been found.

Example with Visual Illustration 🌟

Consider the graph illustrated below with the following edges and weights:

Dijkstra's Algorithm

The edges and their weights are:

  • A to B: 4
  • A to C: 5
  • B to D: 9
  • B to C: 11
  • C to E: 3
  • D to E: 13
  • D to F: 2
  • E to F: 6

Let's find the shortest path from A to all other nodes.

  1. Initialization:

    • Distance: A=0, B=∞, C=∞, D=∞, E=∞, F=∞
    • Unvisited set: {A, B, C, D, E, F}
    • Current node: A
  2. Visit Neighbors of A:

    • Update distance for B: Distance[B] = 0 + 4 = 4
    • Update distance for C: Distance[C] = 0 + 5 = 5
    • Distance: A=0, B=4, C=5, D=∞, E=∞, F=∞
  3. Mark A as Visited:

    • Unvisited set: {B, C, D, E, F}
  4. Select B as the Next Current Node:

    • Current node: B
  5. Visit Neighbors of B:

    • Update distance for D: Distance[D] = 4 + 9 = 13
    • Update distance for C: Distance[C] = min(5, 4 + 11) = 5
    • Distance: A=0, B=4, C=5, D=13, E=∞, F=∞
  6. Mark B as Visited:

    • Unvisited set: {C, D, E, F}
  7. Select C as the Next Current Node:

    • Current node: C
  8. Visit Neighbors of C:

    • Update distance for E: Distance[E] = 5 + 3 = 8
    • Distance: A=0, B=4, C=5, D=13, E=8, F=∞
  9. Mark C as Visited:

    • Unvisited set: {D, E, F}
  10. Select E as the Next Current Node:

    • Current node: E
  11. Visit Neighbors of E:

    • Update distance for F: Distance[F] = 8 + 6 = 14
    • Distance: A=0, B=4, C=5, D=13, E=8, F=14
  12. Mark E as Visited:

    • Unvisited set: {D, F}
  13. Select D as the Next Current Node:

    • Current node: D
  14. Visit Neighbors of D:

    • Update distance for F: Distance[F] = min(14, 13 + 2) = 15
    • Distance: A=0, B=4, C=5, D=13, E=8, F=14
  15. Mark D as Visited:

    • Unvisited set: {F}
  16. Select F as the Next Current Node:

    • Current node: F
  17. Mark F as Visited:

    • Unvisited set: {}

At this point, all nodes have been visited, and the shortest distances from A are:

  • A to B: 4
  • A to C: 5
  • A to D: 13
  • A to E: 8
  • A to F: 14

Python Implementation 🐍

Here’s a Python implementation of Dijkstra's Algorithm:

import heapq

def dijkstra(graph, start):
    # Priority queue to store (distance, node)
    priority_queue = [(0, start)]
    # Dictionary to store the shortest path to each node
    shortest_paths = {start: (None, 0)}
    visited = set()

    while priority_queue:
        current_distance, current_node = heapq.heappop(priority_queue)

        if current_node in visited:
            continue

        visited.add(current_node)

        for neighbor, weight in graph[current_node].items():
            distance = current_distance + weight

            if neighbor not in shortest_paths or distance < shortest_paths[neighbor][1]:
                shortest_paths[neighbor] = (current_node, distance)
                heapq.heappush(priority_queue, (distance, neighbor))

    return shortest_paths

# Define the graph
graph = {
    'A': {'B': 4, 'C': 5},
    'B': {'D': 9, 'C': 11},
    'C': {'E': 3},
    'D': {'E': 13, 'F': 2},
    'E': {'F': 6},
    'F': {}
}

# Compute the shortest paths
start_node = 'A'
shortest_paths = dijkstra(graph, start_node)

# Output the shortest paths
for node, (prev, dist) in shortest_paths.items():
    path = []
    current = node
    while current:
        path.append(current)
        current = shortest_paths[current][0]
    path.reverse()
    print(f"Shortest path to {node}: {dist}, Path: {' -> '.join(path)}")
Enter fullscreen mode Exit fullscreen mode

Conclusion πŸŽ‰

Dijkstra's Algorithm is a powerful tool for finding the shortest path in a weighted graph. By understanding and implementing this algorithm, you can solve various real-world problems, such as network routing, geographic mapping, and more. With this detailed explanation and example, you should now have a solid grasp of how Dijkstra's Algorithm works and how to apply it in your own projects.

please subscribe to my YouTube channel to support my channel and get more web development tutorials.

Happy coding! πŸš€

Follow and Subscribe:

Top comments (2)

Collapse
 
heyeasley profile image
heyeasley πŸ“πŸ₯­

Cool. Learningful.

Collapse
 
matin_mollapur profile image
Matin Mollapur

great article! really helped me understand dijkstra's algorithm better. the step-by-step explanation and visual example were super helpful. thanks for breaking it down in such a clear way. gonna try implementing this in my next project for sure.