@@ -17,25 +17,28 @@ def print_distance_and_paths(distance: list[float], paths: list[list[int]], src:
17
17
print (f"{ vertex } \t \t { dist } \t \t \t \t { path_str } " )
18
18
19
19
20
- def check_negative_cycle (graph : list [Edge ], distance : list [float ],
21
- predecessor : list [int ]) -> bool :
20
+ def check_negative_cycle (
21
+ graph : list [Edge ], distance : list [float ], predecessor : list [int ]
22
+ ) -> bool :
22
23
"""
23
24
Checks if there is a negative weight cycle reachable from the source vertex.
24
25
If found, return True, indicating a negative cycle.
25
26
"""
26
27
for edge in graph :
27
- if (distance [edge .src ] != float ("inf" ) and
28
- distance [edge .src ] + edge .weight
29
- < distance [edge .dst ]):
28
+ if (
29
+ distance [edge .src ] != float ("inf" )
30
+ and distance [edge .src ] + edge .weight < distance [edge .dst ]
31
+ ):
30
32
# Update predecessors to indicate a cycle for affected paths
31
33
# Use -1 as a marker for negative cycle detection
32
34
predecessor [edge .dst ] = - 1
33
35
return True
34
36
return False
35
37
36
38
37
- def reconstruct_paths (predecessor : list [int ],
38
- vertex_count : int , src : int ) -> list [list [int ]]:
39
+ def reconstruct_paths (
40
+ predecessor : list [int ], vertex_count : int , src : int
41
+ ) -> list [list [int ]]:
39
42
"""
40
43
Reconstructs the shortest paths from the source vertex to
41
44
each vertex using the predecessor list.
@@ -56,8 +59,9 @@ def reconstruct_paths(predecessor: list[int],
56
59
return paths
57
60
58
61
59
- def bellman_ford (graph : list [Edge ],
60
- vertex_count : int , src : int ) -> tuple [list [float ], list [list [int ]]]:
62
+ def bellman_ford (
63
+ graph : list [Edge ], vertex_count : int , src : int
64
+ ) -> tuple [list [float ], list [list [int ]]]:
61
65
"""
62
66
Returns the shortest paths from a vertex src to all other vertices,
63
67
including path reconstruction.
@@ -69,8 +73,10 @@ def bellman_ford(graph: list[Edge],
69
73
# Step 1: Relax edges repeatedly
70
74
for _ in range (vertex_count - 1 ):
71
75
for edge in graph :
72
- if (distance [edge .src ] != float ("inf" ) and
73
- distance [edge .src ] + edge .weight < distance [edge .dst ]):
76
+ if (
77
+ distance [edge .src ] != float ("inf" )
78
+ and distance [edge .src ] + edge .weight < distance [edge .dst ]
79
+ ):
74
80
distance [edge .dst ] = distance [edge .src ] + edge .weight
75
81
predecessor [edge .dst ] = edge .src
76
82
@@ -97,8 +103,9 @@ def bellman_ford(graph: list[Edge],
97
103
98
104
for i in range (E ):
99
105
print (f"Edge { i + 1 } " )
100
- src , dest , weight = map (int ,
101
- input ("Enter source, destination, weight: " ).strip ().split ())
106
+ src , dest , weight = map (
107
+ int , input ("Enter source, destination, weight: " ).strip ().split ()
108
+ )
102
109
if src < 0 or src >= V or dest < 0 or dest >= V :
103
110
print (f"Invalid vertices: src and dest should be between 0 and { V - 1 } " )
104
111
continue
0 commit comments