使用Bellman Ford算法检测负循环

时间:2014-12-29 17:18:32

标签: java algorithm

我知道这有点触及,但我关注的是Princeton's course on Algorithm。我试图使用Bellman Ford算法来检测边缘加权有向图中的负循环。

There is a negative cycle reachable from the source if and only if the queue is 
nonempty after the Vth pass through all the edges. Moreover, the subgraph of 
edges in our edgeTo[] array must contain a negative cycle.

完整的代码实现位于:BellmanFordSP.javaEdgeWeightedDirectedCycle.java。具体来说,我在这一点上陷入困​​境:

public class BellmanFordSP 
{
    private double[] distTo;   // distTo[v] = distance  of shortest s->v path
    private DirectedEdge[] edgeTo; // edgeTo[v] = last edge on shortest s->v path
    private boolean[] onQueue;     // onQueue[v] = is v currently on the queue?
    private Queue<Integer> queue;  // queue of vertices to relax
    private int cost;              // number of calls to relax()
    private Iterable<DirectedEdge> cycle;// negative cycle (or null if no such cycle)

    // Computes a shortest paths tree from s to every other vertex
    public BellmanFordSP(EdgeWeightedDigraph G, int s) 
    {
        distTo  = new double[G.V()];
        edgeTo  = new DirectedEdge[G.V()];
        onQueue = new boolean[G.V()];
        for (int v = 0; v < G.V(); v++)
            distTo[v] = Double.POSITIVE_INFINITY;
        distTo[s] = 0.0;

        // Bellman-Ford algorithm
        queue = new Queue<Integer>();
        queue.enqueue(s);
        onQueue[s] = true;
        while (!queue.isEmpty() && !hasNegativeCycle()) 
        {
            int v = queue.dequeue();
            onQueue[v] = false;
            relax(G, v);
        }
    }

    // relax vertex v and put other endpoints on queue if changed
    // G.V() gives number of vertices in G
    // G.adj(v) returns an Iterable of edges emanating from vertex v.
    private void relax(EdgeWeightedDigraph G, int v) 
    {
        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++ % G.V() == 0)    // <-- what does this check do ?
                findNegativeCycle();
        }
    }

    // Is there a negative cycle reachable from the source vertex s?
    public boolean hasNegativeCycle() 
    {
        return cycle != null;
    }


    // Returns a negative cycle reachable from the source vertex s
    public Iterable<DirectedEdge> negativeCycle() 
    {
        return cycle;
    }

    // by finding a cycle in predecessor graph
    private void findNegativeCycle() 
    {
        int V = edgeTo.length;
        EdgeWeightedDigraph spt = new EdgeWeightedDigraph(V);
        for (int v = 0; v < V; v++)
            if (edgeTo[v] != null)
                spt.addEdge(edgeTo[v]);

        EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(spt);
        cycle = finder.cycle();
    }

这种情况表示什么:cost++ % G.V() == 0。 为什么我们只在这个特定条件下检查负循环?

2 个答案:

答案 0 :(得分:1)

通常,Bellman-Ford算法进行| V | -1步放松。如果要检测负循环,则必须再次运行松弛。如果你仍然可以再次放松网络,它确实有一个负面的循环。

这条件正在检查的是什么,如果这是你要求放松的时间。

请注意,宽松边缘并非始终是循环的一部分,它可能是循环中可到达的边缘。

答案 1 :(得分:0)

您可以查看我在stackoverflow Bellman ford queue based approach from Sedgewick and Wayne - Algorithms, 4th edition

上询问的问题的答案
if (cost++ % G.V() == 0)    
    findNegativeCycle();

此条件用于定期检测循环。 当条件为真时,没有必要完全发生循环。在此条件成立之后可以发生循环,在这种情况下,它必须等待下一次,直到此条件cost++ % G.V() == 0为真以找到循环。如果使用任何其他数字(接近边数或顶点数的小数)作为除数而不是顶点数,算法将起作用。除数仅用于定期检查周期。