Graph Theory37 sections · 1633 units
Open in Course

SPFA Cycle Detection

(Counting relaxations)

To detect negative cycles with SPFA, count how many times each node is relaxed. If any node is relaxed nn or more times, a negative cycle exists. Why?

Each relaxation extends the path by one edge. If a node needs n\geq n relaxations, the path uses n\geq n edges, implying a cycle. If the path keeps improving, the cycle is negative. This is simpler than running nn full iterations. You detect the cycle as soon as a node is relaxed nn times, which can happen early if the cycle is small.