Description

Dijkstra's Algorithm is an algorithm used to find the shortest path from a single source vertex to all other vertices in a graph with non-negative edge weights. The algorithm uses a greedy approach, repeatedly selecting the vertex with the minimum distance, and updates the distances to neighboring vertices.

This algorithm works on graphs represented as adjacency lists or adjacency matrices and is one of the most popular methods for finding shortest paths in graphs with positive edge weights.

Main Steps of Dijkstra's Algorithm:

  1. Initialize the distance to all vertices as infinity (∞), except for the starting vertex, which is set to 0.
  1. Use a minimum priority queue (min-heap) to store vertices along with their current shortest distances.
  1. Extract the vertex with the minimum distance from the priority queue and update the distances to its neighboring vertices.
  1. Repeat steps 2 and 3 until all vertices have been processed.

The algorithm guarantees that we find the shortest paths from the starting vertex to all other vertices in the graph.


Algorithm Steps:

  1. Initialize distances: Set distance to all vertices to infinity, except the start vertex, which has a distance of 0.
  1. Push to Priority Queue: Add the starting vertex to the priority queue with distance 0.
  1. Process Vertices: In a loop, extract the vertex with the minimum distance from the priority queue and update the distance to its neighbors if finding a path through this vertex is shorter.
  1. Repeat: Continue until all vertices are processed.

Example Output:

Distances from vertex A: {'A': 0, 'B': 1, 'C': 3, 'D': 4}

Step-by-Step Explanation:

  1. We start at vertex 'A', which has a distance of 0.
  1. The algorithm adds all its neighboring vertices (in this case, 'B' and 'C') to the priority queue, assigning them distances 1 and 4, respectively.
  1. By popping vertices with the minimum distance from the priority queue, the algorithm updates the distances to neighboring vertices whenever a shorter path through the current vertex is found.
  1. The algorithm completes when all reachable vertices have been processed.

Python Implementation

import heapq

def dijkstra(graph, start):
    # graph: dictionary where keys are vertices and values are lists of tuples (neighbor, weight)
    # start: starting vertex
    distances = {vertex: float('infinity') for vertex in graph}  # Initialize distances as infinity
    distances[start] = 0  # Distance to the start vertex is 0
    priority_queue = [(0, start)]  # Min-heap storing tuples of (distance, vertex)

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

        # If the extracted distance is greater than the recorded distance, skip processing
        if current_distance > distances[current_vertex]:
            continue

        # Process all neighboring vertices
        for neighbor, weight in graph[current_vertex]:
            distance = current_distance + weight

            # If a shorter path to the neighbor is found, update it
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(priority_queue, (distance, neighbor))

    return distances

# Example Usage:
graph = {
    'A': [('B', 1), ('C', 4)],  # Vertex A connected to B (weight 1) and C (weight 4)
    'B': [('A', 1), ('C', 2), ('D', 5)],  # Vertex B connected to A (weight 1), C (weight 2), and D (weight 5)
    'C': [('A', 4), ('B', 2), ('D', 1)],  # Vertex C connected to A (weight 4), B (weight 2), and D (weight 1)
    'D': [('B', 5), ('C', 1)]   # Vertex D connected to B (weight 5) and C (weight 1)
}

start_vertex = 'A'
distances = dijkstra(graph, start_vertex)

print(f"Distances from vertex {start_vertex}: {distances}")

Output:

Distances from vertex A: {'A': 0, 'B': 1, 'C': 3, 'D': 4}

Complexity of Dijkstra's Algorithm:

  • Time Complexity: O((V + E) log V), where V is the number of vertices and E is the number of edges. The execution time depends on extracting the minimum element from the priority queue and updating edge distances.
  • Space Complexity: O(V + E), where V is the number of vertices and E is the number of edges, as we store the graph adjacency list, distance array/dictionary, and priority queue.

Applications of Dijkstra's Algorithm:

  1. Routing: Used for finding optimal data transmission paths in networks (e.g., internet routers).
  1. Path Planning: Used in navigation systems (GPS) to find the shortest routes between locations.
  1. Graph Analysis: Applied in analyzing transport networks, such as calculating the fastest travel routes.
  1. Cost Estimation: Can be used to calculate the minimum cost of achieving goals in optimization problems.

Dijkstra's Algorithm is an efficient and widely used method for working with graphs containing non-negative edge weights.