|
| 1 | +""" |
| 2 | +Bellman-Ford Algorithm |
| 3 | +---------------------- |
| 4 | +Description: |
| 5 | + Computes shortest paths from a single source vertex to all other vertices in a weighted graph. |
| 6 | + Supports negative weight edges and detects negative weight cycles. |
| 7 | +
|
| 8 | +Usage: |
| 9 | + Call bellman_ford(vertices, edges, source) with: |
| 10 | + - vertices: list of node labels |
| 11 | + - edges: list of tuples (u, v, weight) |
| 12 | + - source: starting node label |
| 13 | +
|
| 14 | +Time Complexity: O(V * E) |
| 15 | +Space Complexity: O(V) |
| 16 | +
|
| 17 | +
|
| 18 | +""" |
| 19 | + |
| 20 | +def bellman_ford(vertices, edges, source): |
| 21 | + # Validate that the source exists in the graph |
| 22 | + if source not in vertices: |
| 23 | + raise ValueError(f"Source vertex '{source}' not found in graph.") |
| 24 | + |
| 25 | + # Validate that all edge endpoints exist in the graph |
| 26 | + for u, v, _ in edges: |
| 27 | + if u not in vertices or v not in vertices: |
| 28 | + raise ValueError(f"Edge contains undefined vertex: ({u}, {v})") |
| 29 | + |
| 30 | + # Step 1: Initialize distances from source to all vertices as infinite |
| 31 | + distance = {v: float('inf') for v in vertices} |
| 32 | + distance[source] = 0 |
| 33 | + |
| 34 | + # Step 2: Relax all edges |V| - 1 times |
| 35 | + for _ in range(len(vertices) - 1): |
| 36 | + for u, v, w in edges: |
| 37 | + # If the current path offers a shorter route, update the distance |
| 38 | + if distance[u] != float('inf') and distance[u] + w < distance[v]: |
| 39 | + distance[v] = distance[u] + w |
| 40 | + |
| 41 | + # Step 3: Check for negative weight cycles |
| 42 | + for u, v, w in edges: |
| 43 | + if distance[u] != float('inf') and distance[u] + w < distance[v]: |
| 44 | + raise ValueError("Graph contains a negative weight cycle.") |
| 45 | + |
| 46 | + return distance |
| 47 | + |
| 48 | + |
| 49 | +# ------------------ Test Cases ------------------ |
| 50 | + |
| 51 | +def run_tests(): |
| 52 | + print("Running Bellman-Ford test cases...\n") |
| 53 | + |
| 54 | + # Test Case 1: Basic graph with positive weights |
| 55 | + vertices1 = ['A', 'B', 'C', 'D'] |
| 56 | + edges1 = [ |
| 57 | + ('A', 'B', 1), |
| 58 | + ('B', 'C', 3), |
| 59 | + ('A', 'C', 10), |
| 60 | + ('C', 'D', 2), |
| 61 | + ('B', 'D', 2) |
| 62 | + ] |
| 63 | + print("Test Case 1:", bellman_ford(vertices1, edges1, 'A')) |
| 64 | + |
| 65 | + # Test Case 2: Graph with negative weights but no cycle |
| 66 | + vertices2 = ['X', 'Y', 'Z'] |
| 67 | + edges2 = [ |
| 68 | + ('X', 'Y', 4), |
| 69 | + ('Y', 'Z', -2), |
| 70 | + ('X', 'Z', 5) |
| 71 | + ] |
| 72 | + print("Test Case 2:", bellman_ford(vertices2, edges2, 'X')) |
| 73 | + |
| 74 | + # Test Case 3: Graph with a negative weight cycle |
| 75 | + vertices3 = ['P', 'Q', 'R'] |
| 76 | + edges3 = [ |
| 77 | + ('P', 'Q', 1), |
| 78 | + ('Q', 'R', -1), |
| 79 | + ('R', 'P', -1) |
| 80 | + ] |
| 81 | + try: |
| 82 | + print("Test Case 3:", bellman_ford(vertices3, edges3, 'P')) |
| 83 | + except ValueError as e: |
| 84 | + print("Test Case 3: Exception caught -", e) |
| 85 | + |
| 86 | + # Test Case 4: Invalid source vertex |
| 87 | + try: |
| 88 | + print("Test Case 4:", bellman_ford(['A', 'B'], [('A', 'B', 2)], 'Z')) |
| 89 | + except ValueError as e: |
| 90 | + print("Test Case 4: Exception caught -", e) |
| 91 | + |
| 92 | + # Test Case 5: Edge with undefined vertex |
| 93 | + try: |
| 94 | + print("Test Case 5:", bellman_ford(['A', 'B'], [('A', 'C', 2)], 'A')) |
| 95 | + except ValueError as e: |
| 96 | + print("Test Case 5: Exception caught -", e) |
| 97 | + |
| 98 | + |
| 99 | +if __name__ == "__main__": |
| 100 | + run_tests() |
0 commit comments