我正在尝试改进 Bellman-Ford 算法的性能,我想知道改进是否正确。
我运行放松部分不是 V-1 而是 V 次,我得到了一个布尔变量,true
如果在外循环的迭代期间发生任何放松,则设置该变量。如果在 n 处没有放松。n <= V 的迭代,它从最短路径的循环返回,但如果它在 n = V 迭代时松弛,这意味着我们有一个负循环。
我认为它可能会改善运行时间,因为有时我们不必迭代 V-1 次来找到最短路径,并且我们可以更早地返回,而且它也比使用另一个代码块检查循环更优雅。
AdjacencyListALD graph;
int[] distTo;
int[] edgeTo;
public BellmanFord(AdjacencyListALD g)
{
graph = g;
}
public int findSP(int source, int dest)
{
// initialization
distTo = new int[graph.SIZE];
edgeTo = new int[graph.SIZE];
for (int i = 0;i<graph.SIZE;i++)
{
distTo[i] = Integer.MAX_VALUE;
}
distTo[source] = 0;
// relaxing V-1 times + 1 for checking negative cycle = V times
for(int i = 0;i<(graph.SIZE);i++)
{
boolean hasRelaxed=false;
for(int j = 0;j<graph.SIZE;j++)
{
for(int x=0;x<graph.sources[j].length;x++)
{
int s = j;
int d = graph.sources[j].get(x).label;
int w = graph.sources[j].get(x).weight;
if(distTo[d] > distTo[s]+w)
{
distTo[d] = distTo[s]+w;
hasRelaxed = true;
}
}
}
if(!hasRelaxed)
return distTo[dest];
}
System.out.println("Negative cycle detected");
return -1;
}