0
votes

I know that Bellman-Ford algorithm takes at most |V| - 1 iterations to find the shortest path if the graph does not contain a negative weight cycle. Is there a way to modify Bellman-Ford algorithm so it will find the shortest path in 1 iteration?

1
No, otherwise that would have been the algorithm - amit
Make sure that |V| <= 2? - twalberg
No,The longest path in a simple graph with distinct nodes can have atmost V-1 edges thus V-1 iterations, see the proof on wiki you will understand - sashas

1 Answers

0
votes

No, worst-case running time of Bellman-Ford is O(E*V) which comes because of the necessity to iterate over the graph over V-1 times. However, we can practically improve Bellman-Ford to a running time of O(E+V) by using a queue-based bellman-ford variant.

Here's the queue-based Bellman-Ford implementation. Code inspired from the booksite Algorithms, 4th edition, Robert Sedgewick and Kevin Wayne

private void findShortestPath(int src) {
    queue.add(src);
    distTo[src] = 0;
    edgeTo[src] = -1;
    while (!queue.isEmpty()) {
        int v = queue.poll();
        onQueue[v] = false;
        for (Edge e : adj(v)){
            int w = e.dest;
            if (distTo[w] > distTo[v] + e.weight) {
                distTo[w] = distTo[v] + e.weight;
                edgeTo[w] = v;
            }
            if (!onQueue[w]) {
                onQueue[w] = true;
                queue.add(w);
            }

            //Find if a negative cycle exists after every V passes
            if (cost++ % V == 0) {
                if (findNegativeCycle())
                    return;
            }
        }
    }
}

The worst case running time of this algorithm is still O(E*V) but, in this algorithm typically runs in O(E+V) practically.