I studied the queue-based approach for the Bellman-Ford algorithm for the shortest path with one source from Robert Sedgewick and Kevin Wayne - Algorithms, 4th edition source code for the algorithm from the book is available at this link http://algs4.cs.princeton.edu/ 44sp / BellmanFordSP.java .
I have two points, one of which is doubt, and the other is a suggestion for improving the code.
In the above approach, the following code for the attenuation method is to relax the distance to the peaks.
for (DirectedEdge e : G.adj(v)) { int w = e.to(); if (distTo[w] > distTo[v] + e.weight()) { distTo[w] = distTo[v] + e.weight(); edgeTo[w] = e; if (!onQueue[w]) { queue.enqueue(w); onQueue[w] = true; } } if (cost++ % GV() == 0){ findNegativeCycle(); } }
In this method, the condition below is used until a negative cycle is found.
if (cost++ % GV() == 0){ findNegativeCycle(); }
Above, they divide the cost by the number of vertices in the graph to check the negative cycle . Maybe because relaxation is performed V-1 times, and if relaxation is performed for Vth time, this means that it has a cycle, where V is the number of vertices.
But I think that in the queue-based approach, they use a divisor to check at a regular interval if the cycle has occurred or not. A cycle may occur before or immediately after the condition is higher. If the cycle occurred after the above condition is true, then the algorithm must wait until the next time condition true to detect the cycle, there is no need for the cycle to happen exactly if (cost++ % GV() == 0) - true. Therefore, I think that divisor can be any number small enough so that we can check the loop after the corresponding time interval. Am I right in thinking about this?
The recommendation for code improvement is that the findNegativeCycle() method can be used to return true if a loop has occurred. Thus. this condition -
if (cost++ % GV() == 0) { findNegativeCycle(); }
Can be changed to -
if (cost++ % GV() == 0) if(findNegativeCycle()){ return; }
In the for loop, the loop continues to work, even if the findNegativeCycle() method found the loop. Thus, we can return if the cycle occurred instead of processing the rest of the cycle.
Share your thoughts above 2 points. Thanks in advance.
source share