Dijkstra Shortest Path

Finds shortest path between nodes in a weighted graph. Essential for routing, navigation, and network optimization problems.

Python7/16/2025
#algorithms#graph#shortest-path
Python
import heapq

def dijkstra(graph, start, end):
    distances = {node: float('inf') for node in graph}
    distances[start] = 0
    previous = {}
    pq = [(0, start)]
    
    while pq:
        current_dist, current = heapq.heappop(pq)
        
        if current == end:
            path = []
            while current in previous:
                path.append(current)
                current = previous[current]
            path.append(start)
            return path[::-1], distances[end]
        
        if current_dist > distances[current]:
            continue
            
        for neighbor, weight in graph[current].items():
            distance = current_dist + weight
            
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                previous[neighbor] = current
                heapq.heappush(pq, (distance, neighbor))
    
    return None, float('inf')
...
Loading comments...