Dijkstra implementation keeps giving wrong shortest paths. #14214
Answered
by
MaxValueBuilder
PanthersHowl
asked this question in
Q&A
-
|
My Dijkstra implementation keeps giving wrong shortest paths. Getting infinite loops or incorrect distances. |
Beta Was this translation helpful? Give feedback.
Answered by
MaxValueBuilder
Jan 26, 2026
Replies: 1 comment
-
|
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[neighbor] = current
heapq.heappush(pq, (distance, neighbor))
return distances, prev_node
# Example usage
graph = {
'A': {'B': 4, 'C': 2},
'B': {'A': 4, 'C': 1, 'D': 5},
'C': {'A': 2, 'B': 1, 'D': 8},
'D': {'B': 5, 'C': 8}
}
distances, prev = dijkstra(graph, 'A')
print(distances) # {'A': 0, 'B': 2, 'C': 2, 'D': 7} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
PanthersHowl
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a production-ready Dijkstra's algorithm with priority queue: