CodexBloom - Programming Q&A Platform

Handling Negative Edge Weights in Bellman-Ford Algorithm - Unexpected Result in Python 3.9

πŸ‘€ Views: 76 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
algorithms bellman-ford graph-theory Python

I'm upgrading from an older version and I tried several approaches but none seem to work... Quick question that's been bugging me - I've been banging my head against this for hours... I'm currently implementing the Bellman-Ford algorithm in Python 3.9 for finding the shortest paths in a graph with potentially negative edge weights. However, I'm working with an unexpected result where the algorithm fails to correctly identify the shortest path when negative weights are involved. I've set up my graph as a list of edges, and after running the algorithm, the distances array is not reflecting the correct shortest distances, especially when negative weight edges are included. Here’s the code I’m working with: ```python class Graph: def __init__(self, vertices): self.V = vertices # Number of vertices self.edges = [] # List of edges def add_edge(self, u, v, w): self.edges.append((u, v, w)) # (source, destination, weight) def bellman_ford(self, src): distances = [float('inf')] * self.V distances[src] = 0 for _ in range(self.V - 1): for u, v, w in self.edges: if distances[u] != float('inf') and distances[u] + w < distances[v]: distances[v] = distances[u] + w # Check for negative-weight cycles for u, v, w in self.edges: if distances[u] != float('inf') and distances[u] + w < distances[v]: print("Graph contains negative weight cycle") return None return distances # Example usage: g = Graph(5) g.add_edge(0, 1, -1) g.add_edge(0, 2, 4) g.add_edge(1, 2, 3) g.add_edge(1, 3, 2) g.add_edge(1, 4, 2) g.add_edge(3, 1, 1) g.add_edge(4, 3, -3) result = g.bellman_ford(0) print(result) # Expected shortest paths ``` The above code prints the distances correctly for positive weights, but when I add negative edge weights, I notice that the distances are not updated properly. I checked the conditions for updating the distances but need to seem to find where I might be going wrong. I’ve tried adding print statements to debug the values of `distances` during each iteration, but it seems that the updates are performed as expected in the first few iterations, only to revert back or not compute correctly later on. Could there be a logical scenario or a common pitfall related to negative weights that I might be overlooking? Any insights or suggestions to resolve this would be greatly appreciated! Thanks for your help in advance! Cheers for any assistance! For reference, this is a production mobile app. I'm open to any suggestions. My development environment is macOS. What would be the recommended way to handle this?