I was studying queue-based
approach for Bellman-Ford algorithm
for single source shortest path from Robert Sedgewick and Kevin Wayne - Algorit
Accordingly, to implement negativeCycle() BellmanFordSP.java builds an edge-weighted digraph from the edges in edgeTo[] and looks for a cycle in that digraph. To find the cycle, it uses EdgeWeightedDirectedCycle.java, a version of DirectedCycle.java from Section 4.3, adapted to work for edge-weighted digraphs. We amortize the cost of this check by performing this check only after every Vth call to relax().
In other words, you can check more often, but then you risk performance loss.
while
loop in the constructor. However, in the worst case the relax
method can detect the cycle by checking first edge in the for
loop, and instead of exiting it will continue and check other edges (max V-2
of them). With your suggested improvement that can save significant amount of time.