CodexBloom - Programming Q&A Platform

Unexpected Behavior in Dijkstra's Algorithm with Negative Edge Weights in Python

👀 Views: 65 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
algorithms dijkstra graph-theory Python

I'm updating my dependencies and I've been banging my head against this for hours. I'm currently implementing Dijkstra's algorithm to find the shortest path in a graph represented with an adjacency list in Python. However, I'm running into unexpected behavior when I include negative edge weights. I expected Dijkstra's algorithm to handle only non-negative weights, but I'm not sure how to manage cases where these weights appear in my graph. My implementation returns a wrong path and an unexpected distance value. Here's a snippet of my code: ```python import heapq from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def add_edge(self, u, v, weight): self.graph[u].append((v, weight)) def dijkstra(self, start): distances = {node: float('inf') for node in self.graph} distances[start] = 0 priority_queue = [(0, start)] # (distance, node) while priority_queue: current_distance, current_node = heapq.heappop(priority_queue) if current_distance > distances[current_node]: continue for neighbor, weight in self.graph[current_node]: distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(priority_queue, (distance, neighbor)) return distances # Creating the graph and adding edges with negative weight g = Graph() g.add_edge('A', 'B', 4) g.add_edge('A', 'C', 1) g.add_edge('C', 'B', -2) g.add_edge('B', 'D', 2) g.add_edge('C', 'D', 5) distances = g.dijkstra('A') print(distances) # Expecting {'A': 0, 'B': 2, 'C': 1, 'D': 4} but getting wrong results ``` In this example, I'm adding a negative edge from C to B. I would expect Dijkstra's algorithm to correctly compute the shortest distance, but instead, it seems to fail and returns incorrect distances for nodes. Is there a recommended approach to handle graphs with negative weights, or do I need to switch to a different algorithm like Bellman-Ford? Any insights or improvements to my current approach would be greatly appreciated! Any help would be greatly appreciated! This is part of a larger microservice I'm building. Any advice would be much appreciated.