Returns shortest paths from a vertex src to all other vertices. >>> edges = [(2, 1, -10), (3, 2, 3), (0, 3, 5), (0, 1, 4)] >>> g = [{"src": s, "dst": d, "weight": w} for s, d, w in edges] >>> bellman_ford(g, 4, 4, 0) [0.0, -2.0, 8.0, 5.0] >>> g = [{"src": s, "dst": d, "w
(
graph: list[dict[str, int]], vertex_count: int, edge_count: int, src: int
)
| 18 | |
| 19 | |
| 20 | def bellman_ford( |
| 21 | graph: list[dict[str, int]], vertex_count: int, edge_count: int, src: int |
| 22 | ) -> list[float]: |
| 23 | """ |
| 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 |
| 35 | """ |
| 36 | distance = [float("inf")] * vertex_count |
| 37 | distance[src] = 0.0 |
| 38 | |
| 39 | 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"]) |
| 42 | |
| 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: |
| 48 | raise Exception("Negative cycle found") |
| 49 | |
| 50 | return distance |
| 51 | |
| 52 | |
| 53 | if __name__ == "__main__": |
no test coverage detected