Skip to content
Discussion options

You must be logged in to vote

Here's a production-ready Dijkstra's algorithm with priority queue:

import heapq
from collections import defaultdict

def dijkstra(graph, start):
    # Priority queue: (distance, node)
    pq = [(0, start)]
    distances = {node: float('inf') for node in graph}
    distances[start] = 0
    prev_node = {}
    
    while pq:
        current_dist, current = heapq.heappop(pq)
        
        if current_dist > distances[current]:
            continue
            
        for neighbor, weight in graph[current].items():
            distance = current_dist + weight
            
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                prev_node[n…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by PanthersHowl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants