DATA STRUCTURES
🇬🇧UK Edition🇨🇦Canada Edition🌐Global Tech

Dijkstra's Shortest Path Algorithm: Min-Heap Implementation in Python

Dr. Alistair Vance
Dr. Alistair Vance
Principal CS Fellow
Updated 03/09/20267 min read3 views

Graph Routing & Shortest Path

Dijkstra's algorithm computes the minimum distance from a single source node to all other vertices in a non-negatively weighted graph.

python
import heapq

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

    while pq:
        current_dist, current_node = heapq.heappop(pq)

        if current_dist > distances[current_node]:
            continue

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

    return distances

graph = {
    'A': {'B': 4, 'C': 2},
    'B': {'C': 1, 'D': 5},
    'C': {'B': 1, 'D': 8, 'E': 10},
    'D': {'E': 2},
    'E': {}
}
print(dijkstra(graph, 'A'))

Frequently Asked Questions (FAQ)

Q: Does Dijkstra work on negative edge weights?

No, Bellman-Ford algorithm must be used for graphs with negative edge weights.

Dr. Alistair Vance
Written by Dr. Alistair VanceAdSense EEAT Verified

Principal CS Fellow. Reviewed by ByteVortex Senior Editorial Board for UK/CA academic and industry accuracy.