How to implement dijkstra's algorithm in Python?

by jessyca_langosh , in category: Python , a year ago

How to implement dijkstra's algorithm in Python?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lily.simonis , a year ago

@jessyca_langosh 

Dijkstra's algorithm is a popular algorithm for finding the shortest path between two nodes in a graph. It is a greedy algorithm that works by iteratively selecting the node with the smallest known distance from the start node and updating the distances of its neighbors based on the distance from the start node to the current node. Here is some pseudocode that describes the high-level steps of Dijkstra's algorithm:

  1. Initialize the distance to all nodes to be infinity except for the start node, which should have a distance of zero.
  2. Initialize an empty priority queue and add the start node to it.
  3. While the priority queue is not empty:Extract the node with the smallest distance from the priority queue.For each neighbor of the current node:Calculate the distance from the start node to the neighbor through the current node.If this distance is less than the current distance of the neighbor, update the distance of the neighbor and add it to the priority queue.
  4. Return the distances to all nodes.


Here is some example code in Python that implements Dijkstra's algorithm using this pseudocode:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import heapq

def dijkstra(graph, start):
    # Initialize the distances to all nodes to be infinity
    distances = {node: float('inf') for node in graph}
    # Set the distance to the start node to be zero
    distances[start] = 0
    
    # Initialize an empty priority queue
    pq = []
    # Add the start node to the priority queue
    heapq.heappush(pq, (0, start))
    
    while pq:
        # Extract the node with the smallest distance from the priority queue
        distance, node = heapq.heappop(pq)
        if distance > distances[node]:
            continue
        # Update the distances of the neighbors of the current node
        for neighbor, weight in graph[node].items():
            new_distance = distance + weight
            if new_distance < distances[neighbor]:
                distances[neighbor] = new_distance
                heapq.heappush(pq, (new_distance, neighbor))
    
    # Return the distances to all nodes
    return distances

# Example usage
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'))


This should print the following output:

1
{'A': 0, 'B': 5, 'C': 1, 'D': 2, 'E': 4, 'F': 8}


I hope this helps! Let me know if you have any questions.