= Solution
Initialize $d[s]=0$ and every other tentative distance to infinity. The <Bellman-Ford algorithm> repeatedly relaxes every directed edge:
``
for v in V: d[v] = infinity; parent[v] = none
d[s] = 0
repeat |V|-1 times:
changed = false
for each edge (u,v) of weight w:
if d[u] != infinity and d[u] + w < d[v]:
d[v] = d[u] + w
parent[v] = u
changed = true
if not changed: break
for each edge (u,v) of weight w:
if d[u] != infinity and d[u] + w < d[v]:
report a reachable negative-weight cycle
``
An unreachable vertex retains infinity. A reachable negative-weight cycle prevents finite shortest-walk distances for vertices reachable from that cycle, so the detection case must not be reported as an ordinary finite answer. With edge-list scans the worst-case work is \b[$O(|V||E|+|V|)$], conventionally stated as $O(|V||E|)$, and the auxiliary storage is $O(|V|)$ beyond the graph.
Back to article page