Skip to content

Commit 4a30fcd

Browse files
committed
Improved Bellman-Ford Algorithm : Added Path Reconstruction With Better Output Representation
1 parent f8a94a8 commit 4a30fcd

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

graphs/bellman_ford.py

+20-12
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,28 @@ def print_distance_and_paths(distance: list[float], paths: list[list[int]], src:
1717
print(f"{vertex}\t\t{dist}\t\t\t\t{path_str}")
1818

1919

20-
def check_negative_cycle(graph: list[Edge], distance: list[float], predecessor: list[int]) -> bool:
20+
def check_negative_cycle(graph: list[Edge], distance: list[float],
21+
predecessor: list[int]) -> bool:
2122
"""
2223
Checks if there is a negative weight cycle reachable from the source vertex.
2324
If found, return True, indicating a negative cycle.
2425
"""
2526
for edge in graph:
26-
if distance[edge.src] != float("inf") and distance[edge.src] + edge.weight < distance[edge.dst]:
27+
if (distance[edge.src] != float("inf") and
28+
distance[edge.src] + edge.weight
29+
< distance[edge.dst]):
2730
# Update predecessors to indicate a cycle for affected paths
28-
predecessor[edge.dst] = -1 # Use -1 as a marker for negative cycle detection
31+
# Use -1 as a marker for negative cycle detection
32+
predecessor[edge.dst] = -1
2933
return True
3034
return False
3135

3236

33-
def reconstruct_paths(predecessor: list[int], vertex_count: int, src: int) -> list[list[int]]:
37+
def reconstruct_paths(predecessor: list[int],
38+
vertex_count: int, src: int) -> list[list[int]]:
3439
"""
35-
Reconstructs the shortest paths from the source vertex to each vertex using the predecessor list.
40+
Reconstructs the shortest paths from the source vertex to
41+
each vertex using the predecessor list.
3642
"""
3743
paths = [[] for _ in range(vertex_count)]
3844
for vertex in range(vertex_count):
@@ -50,9 +56,11 @@ def reconstruct_paths(predecessor: list[int], vertex_count: int, src: int) -> li
5056
return paths
5157

5258

53-
def bellman_ford(graph: list[Edge], vertex_count: int, src: int) -> tuple[list[float], list[list[int]]]:
59+
def bellman_ford(graph: list[Edge],
60+
vertex_count: int, src: int) -> tuple[list[float], list[list[int]]]:
5461
"""
55-
Returns the shortest paths from a vertex src to all other vertices, including path reconstruction.
62+
Returns the shortest paths from a vertex src to all other vertices,
63+
including path reconstruction.
5664
"""
5765
distance = [float("inf")] * vertex_count
5866
predecessor = [None] * vertex_count # Keeps track of the path predecessors
@@ -61,7 +69,8 @@ def bellman_ford(graph: list[Edge], vertex_count: int, src: int) -> tuple[list[f
6169
# Step 1: Relax edges repeatedly
6270
for _ in range(vertex_count - 1):
6371
for edge in graph:
64-
if distance[edge.src] != float("inf") and distance[edge.src] + edge.weight < distance[edge.dst]:
72+
if (distance[edge.src] != float("inf") and
73+
distance[edge.src] + edge.weight < distance[edge.dst]):
6574
distance[edge.dst] = distance[edge.src] + edge.weight
6675
predecessor[edge.dst] = edge.src
6776

@@ -88,7 +97,8 @@ def bellman_ford(graph: list[Edge], vertex_count: int, src: int) -> tuple[list[f
8897

8998
for i in range(E):
9099
print(f"Edge {i + 1}")
91-
src, dest, weight = map(int, input("Enter source, destination, weight: ").strip().split())
100+
src, dest, weight = map(int,
101+
input("Enter source, destination, weight: ").strip().split())
92102
if src < 0 or src >= V or dest < 0 or dest >= V:
93103
print(f"Invalid vertices: src and dest should be between 0 and {V - 1}")
94104
continue
@@ -101,6 +111,4 @@ def bellman_ford(graph: list[Edge], vertex_count: int, src: int) -> tuple[list[f
101111
shortest_distance, paths = bellman_ford(graph, V, source)
102112
print_distance_and_paths(shortest_distance, paths, source)
103113
except ValueError:
104-
print("Please enter valid integer inputs.")
105-
except Exception as e:
106-
print(e)
114+
print("Invalid input. Please enter valid integers.")

0 commit comments

Comments
 (0)