Bellman Ford Negative Cycle Detect

Detect negative cycles in weighted graphs using Bellman-Ford for arbitrage detection.

PythonData Integrity

Code

pythonsnippet
11 lines
def bellman_ford(edges, vertices, source):
    dist = {v: float('inf') for v in vertices}
    dist[source] = 0
    for _ in range(len(vertices) - 1):
        for u, v, w in edges:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
    for u, v, w in edges:
        if dist[u] + w < dist[v]:
            return None, True
    return dist, False

How it works

Count the function bellman_ford as the entire surface area of Bellman Ford Negative Cycle Detect.

Repetition is confined to for _ in range(len(vertices) - 1) — the rest of the file is straight-line.

Putting it to use

The main signature reads def bellman_ford(edges, vertices, source)

bellman_ford is the public entry point; everything else in the file exists to support it.

Core lines

dist = {v: float('inf') for v in vertices}

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `bellman_ford` at load time.