Skip to content

Commit 2b50d97

Browse files
committed
Improved Bellman-Ford Algorithm : Added Path Reconstruction With Better Output Representation
1 parent e9e7c96 commit 2b50d97

File tree

1 file changed

+80
-50
lines changed

1 file changed

+80
-50
lines changed

graphs/bellman_ford.py

Lines changed: 80 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,73 +1,103 @@
1-
from __future__ import annotations
1+
from typing import List, Tuple, Dict
2+
from collections import namedtuple
23

4+
Edge = namedtuple("Edge", ["src", "dst", "weight"])
35

4-
def print_distance(distance: list[float], src):
5-
print(f"Vertex\tShortest Distance from vertex {src}")
6-
for i, d in enumerate(distance):
7-
print(f"{i}\t\t{d}")
86

7+
def print_distance_and_paths(distance: List[float], paths: List[List[int]], src: int):
8+
"""
9+
Prints the shortest distance and paths from the source vertex to each vertex.
10+
"""
11+
print(f"Vertex\tShortest Distance from Vertex {src}\tPath")
12+
for vertex, (dist, path) in enumerate(zip(distance, paths)):
13+
path_str = " -> ".join(map(str, path)) if path else "No path"
14+
print(f"{vertex}\t\t{dist}\t\t\t\t{path_str}")
915

10-
def check_negative_cycle(
11-
graph: list[dict[str, int]], distance: list[float], edge_count: int
12-
):
13-
for j in range(edge_count):
14-
u, v, w = (graph[j][k] for k in ["src", "dst", "weight"])
15-
if distance[u] != float("inf") and distance[u] + w < distance[v]:
16+
17+
def check_negative_cycle(graph: List[Edge], distance: List[float], predecessor: List[int]) -> bool:
18+
"""
19+
Checks if there is a negative weight cycle reachable from the source vertex.
20+
If found, return True, indicating a negative cycle.
21+
"""
22+
for edge in graph:
23+
if distance[edge.src] != float("inf") and distance[edge.src] + edge.weight < distance[edge.dst]:
24+
# Update predecessors to indicate a cycle for affected paths
25+
predecessor[edge.dst] = -1 # Use -1 as a marker for negative cycle detection
1626
return True
1727
return False
1828

1929

20-
def bellman_ford(
21-
graph: list[dict[str, int]], vertex_count: int, edge_count: int, src: int
22-
) -> list[float]:
30+
def reconstruct_paths(predecessor: List[int], vertex_count: int, src: int) -> List[List[int]]:
31+
"""
32+
Reconstructs the shortest paths from the source vertex to each vertex using the predecessor list.
33+
"""
34+
paths = [[] for _ in range(vertex_count)]
35+
for vertex in range(vertex_count):
36+
if predecessor[vertex] == -1:
37+
paths[vertex] = ["Negative cycle detected"]
38+
elif predecessor[vertex] is not None:
39+
path = []
40+
current = vertex
41+
while current is not None:
42+
path.insert(0, current)
43+
if current == src:
44+
break
45+
current = predecessor[current]
46+
paths[vertex] = path
47+
return paths
48+
49+
50+
def bellman_ford(graph: List[Edge], vertex_count: int, src: int) -> Tuple[List[float], List[List[int]]]:
2351
"""
24-
Returns shortest paths from a vertex src to all
25-
other vertices.
26-
>>> edges = [(2, 1, -10), (3, 2, 3), (0, 3, 5), (0, 1, 4)]
27-
>>> g = [{"src": s, "dst": d, "weight": w} for s, d, w in edges]
28-
>>> bellman_ford(g, 4, 4, 0)
29-
[0.0, -2.0, 8.0, 5.0]
30-
>>> g = [{"src": s, "dst": d, "weight": w} for s, d, w in edges + [(1, 3, 5)]]
31-
>>> bellman_ford(g, 4, 5, 0)
32-
Traceback (most recent call last):
33-
...
34-
Exception: Negative cycle found
52+
Returns the shortest paths from a vertex src to all other vertices, including path reconstruction.
3553
"""
3654
distance = [float("inf")] * vertex_count
55+
predecessor = [None] * vertex_count # Keeps track of the path predecessors
3756
distance[src] = 0.0
3857

58+
# Step 1: Relax edges repeatedly
3959
for _ in range(vertex_count - 1):
40-
for j in range(edge_count):
41-
u, v, w = (graph[j][k] for k in ["src", "dst", "weight"])
60+
for edge in graph:
61+
if distance[edge.src] != float("inf") and distance[edge.src] + edge.weight < distance[edge.dst]:
62+
distance[edge.dst] = distance[edge.src] + edge.weight
63+
predecessor[edge.dst] = edge.src
4264

43-
if distance[u] != float("inf") and distance[u] + w < distance[v]:
44-
distance[v] = distance[u] + w
45-
46-
negative_cycle_exists = check_negative_cycle(graph, distance, edge_count)
47-
if negative_cycle_exists:
65+
# Step 2: Check for negative weight cycles
66+
if check_negative_cycle(graph, distance, predecessor):
4867
raise Exception("Negative cycle found")
4968

50-
return distance
69+
# Step 3: Reconstruct paths from predecessor list
70+
paths = reconstruct_paths(predecessor, vertex_count, src)
71+
72+
return distance, paths
5173

5274

5375
if __name__ == "__main__":
76+
# Example graph input for testing purposes
5477
import doctest
55-
5678
doctest.testmod()
5779

58-
V = int(input("Enter number of vertices: ").strip())
59-
E = int(input("Enter number of edges: ").strip())
60-
61-
graph: list[dict[str, int]] = [{} for _ in range(E)]
62-
63-
for i in range(E):
64-
print("Edge ", i + 1)
65-
src, dest, weight = (
66-
int(x)
67-
for x in input("Enter source, destination, weight: ").strip().split(" ")
68-
)
69-
graph[i] = {"src": src, "dst": dest, "weight": weight}
70-
71-
source = int(input("\nEnter shortest path source:").strip())
72-
shortest_distance = bellman_ford(graph, V, E, source)
73-
print_distance(shortest_distance, 0)
80+
try:
81+
V = int(input("Enter number of vertices: ").strip())
82+
E = int(input("Enter number of edges: ").strip())
83+
84+
graph: List[Edge] = []
85+
86+
for i in range(E):
87+
print(f"Edge {i + 1}")
88+
src, dest, weight = map(int, input("Enter source, destination, weight: ").strip().split())
89+
if src < 0 or src >= V or dest < 0 or dest >= V:
90+
print(f"Invalid vertices: src and dest should be between 0 and {V - 1}")
91+
continue
92+
graph.append(Edge(src, dest, weight))
93+
94+
source = int(input("\nEnter shortest path source vertex: ").strip())
95+
if source < 0 or source >= V:
96+
print(f"Invalid source: source should be between 0 and {V - 1}")
97+
else:
98+
shortest_distance, paths = bellman_ford(graph, V, source)
99+
print_distance_and_paths(shortest_distance, paths, source)
100+
except ValueError:
101+
print("Please enter valid integer inputs.")
102+
except Exception as e:
103+
print(e)

0 commit comments

Comments
 (0)