0
0
Data Structures Theoryknowledge~6 mins

Dijkstra's algorithm in Data Structures Theory - Full Explanation

Choose your learning style9 modes available
Introduction
Imagine you need to find the shortest path to travel between cities on a map. The challenge is to figure out the quickest route without trying every possible path. Dijkstra's algorithm solves this by efficiently finding the shortest path from one point to all others in a network.
Explanation
Graph Representation
Dijkstra's algorithm works on a graph made of nodes (points) connected by edges (paths). Each edge has a weight that shows the cost or distance to travel that path. The graph can represent roads, networks, or any system with connections.
The graph's nodes and weighted edges form the structure where shortest paths are found.
Initialization
The algorithm starts by setting the distance to the starting node as zero and all other nodes as infinity, meaning they are initially unreachable. It keeps track of visited nodes and updates distances as it explores the graph.
Starting with known distances helps the algorithm update paths step-by-step.
Selecting the Next Node
At each step, the algorithm picks the unvisited node with the smallest known distance. This node is considered the closest next step to explore. It then checks all neighbors of this node to see if a shorter path exists through it.
Choosing the closest unvisited node ensures the shortest paths are found efficiently.
Updating Distances
For each neighbor of the current node, the algorithm calculates the total distance from the start node through the current node. If this distance is less than the previously recorded distance, it updates the neighbor's distance to this new shorter value.
Updating distances helps refine the shortest path estimates as the algorithm progresses.
Termination
The process repeats until all nodes have been visited or the shortest paths to all reachable nodes are found. The final distances represent the shortest path lengths from the start node to every other node in the graph.
The algorithm ends when all shortest paths are determined.
Real World Analogy

Imagine you are in a city and want to find the quickest way to visit all nearby places. You start at your home and always choose the closest unvisited place next, updating your route if you find a shortcut. This way, you efficiently plan your trip without checking every possible route.

Graph Representation → The city map with locations as points and roads as paths with distances
Initialization → Starting at home with known distance zero and other places unknown
Selecting the Next Node → Choosing the nearest unvisited place to go next
Updating Distances → Finding a shortcut to a place and updating your travel plan
Termination → Completing the trip after visiting all reachable places
Diagram
Diagram
┌───────────────┐
│   Start Node  │
└──────┬────────┘
       │
       ▼
┌───────────────┐       ┌───────────────┐
│  Current Node │──────▶│  Neighbor Node│
└──────┬────────┘       └──────┬────────┘
       │                       │
       │ Update Distance       │
       └──────────────────────▶

Process repeats until all nodes visited
This diagram shows the flow of selecting the current node, checking neighbors, updating distances, and repeating until all nodes are visited.
Key Facts
Dijkstra's algorithmAn algorithm to find the shortest path from one node to all others in a weighted graph.
Weighted graphA graph where edges have values representing cost or distance.
Distance initializationStart node distance is zero; all others are set to infinity initially.
Greedy selectionAlways pick the unvisited node with the smallest known distance next.
Distance updateIf a shorter path is found to a neighbor, update its distance.
Code Example
Data Structures Theory
import heapq

def dijkstra(graph, start):
    distances = {node: float('inf') for node in graph}
    distances[start] = 0
    priority_queue = [(0, start)]

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

        if current_distance > distances[current_node]:
            continue

        for neighbor, weight in graph[current_node].items():
            distance = current_distance + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(priority_queue, (distance, neighbor))

    return distances

# Example graph as adjacency list with weights
graph = {
    'A': {'B': 5, 'C': 1},
    'B': {'A': 5, 'C': 2, 'D': 1},
    'C': {'A': 1, 'B': 2, 'D': 4, 'E': 8},
    'D': {'B': 1, 'C': 4, 'E': 3, 'F': 6},
    'E': {'C': 8, 'D': 3},
    'F': {'D': 6}
}

print(dijkstra(graph, 'A'))
OutputSuccess
Common Confusions
Dijkstra's algorithm works with negative edge weights.
Dijkstra's algorithm works with negative edge weights. Dijkstra's algorithm <strong>does not</strong> work correctly with negative edge weights because it assumes that once a node's shortest distance is found, it cannot be improved.
The algorithm finds the shortest path to only one destination.
The algorithm finds the shortest path to only one destination. Dijkstra's algorithm finds the shortest paths from the start node to <strong>all</strong> reachable nodes, not just one.
Summary
Dijkstra's algorithm efficiently finds the shortest paths from one starting point to all others in a weighted graph.
It works by repeatedly selecting the closest unvisited node and updating the shortest distances to its neighbors.
The algorithm requires non-negative edge weights and ends when all reachable nodes have their shortest paths determined.