[英]Bellman-Ford Algorithm
I know that Bellman-Ford algorithm takes at most |V| 我知道Bellman-Ford算法最多需要| V |。 - 1 iterations to find the shortest path if the graph does not contain a negative weight cycle. -如果图形不包含负权重循环,则进行1次迭代以找到最短路径。 Is there a way to modify Bellman-Ford algorithm so it will find the shortest path in 1 iteration? 有没有一种方法可以修改Bellman-Ford算法,以便在1次迭代中找到最短路径?
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. 不,Bellman-Ford的最坏情况运行时间是O(E * V),因为必须在V-1次上迭代图形。 However, we can practically improve Bellman-Ford to a running time of O(E+V) by using a queue-based bellman-ford variant. 但是,通过使用基于队列的Bellman-ford变体,我们实际上可以将Bellman-Ford改进到O(E + V)的运行时间。
Here's the queue-based Bellman-Ford implementation. 这是基于队列的Bellman-Ford实现。 Code inspired from the booksite Algorithms, 4th edition, Robert Sedgewick and Kevin Wayne 代码受书本《 算法》(第4版)的启发,Robert Sedgewick和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. 该算法的最坏情况运行时间仍为O(E * V),但在该算法中通常实际上以O(E + V)运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.