If a graph contains a cycle whose total weight is negative, shortest distances are undefined: you can loop forever to drive the cost down. Bellman-Ford detects this with one extra pass.
Implement has_negative_cycle(n, edges). Return True if the graph contains any negative-weight cycle, otherwise False.
To catch a cycle anywhere in the graph (even one not reachable from vertex 0), start every distance at 0, as if a virtual source pointed at all vertices.
Algorithm:
bellman_ford from Step 1 is provided.
def bellman_ford(n, edges, source):
dist = [float('inf')] * n
dist[source] = 0
for _ in range(n - 1):
for u, v, w in edges:
if dist[u] != float('inf') and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return dist
def has_negative_cycle(n, edges):
"""Return True if any negative-weight cycle exists, else False."""
# TODO: relax from all-zero distances, then test one more pass.
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
If a graph contains a cycle whose total weight is negative, shortest distances are undefined: you can loop forever to drive the cost down. Bellman-Ford detects this with one extra pass.
Implement has_negative_cycle(n, edges). Return True if the graph contains any negative-weight cycle, otherwise False.
To catch a cycle anywhere in the graph (even one not reachable from vertex 0), start every distance at 0, as if a virtual source pointed at all vertices.
Algorithm:
bellman_ford from Step 1 is provided.
Press Run Tests or ββ© to check your solution.