内容转载自https://blog.csdn.net/ak_lady/article/details/70147204
贝尔曼-福特算法是计算从源点到任意一点的最短路径的长度。初始化数组dist[0]为0,dist[i]为无穷大。
以下操作循环执行至多n-1次,n为顶点数:
对于每一条边 edge(Start,End),如果dist[Start] +Weight(Start, End)<dist[End],则令dist[End] =dist[Start]+Weight(Start, End)。若上述操作没有对dist进行更新,说明最短路径已经查找完毕,或者部分点不可达,跳出循环。否则执行下次循环;
为了检测图中是否存在负环路,即权值之和小于0的环路。对于每一条边dge(Start,End),如果存在dist[Start] + Weight(Start, End) < dist[End]的边,则图中存在负环路,即是说改图无法求出单源最短路径。否则数组dist[n]中记录的就是源点s到各顶点的最短路径长度。
Bellman-Ford算法可以大致分为三个部分。
第一,初始化所有点。每一个点保存一个值,表示从原点到达这个点的距离,将原点的值设为0,其它的点的值设为无穷大(表示不可达)。
第二,进行循环,循环下标为从1到n-1(n等于图中点的个数)。在循环内部,遍历所有的边,进行松弛计算。
第三,遍历途中所有的边(edge(u,v)),判断是否存在这样情况:d(v)> d (u) + w(u,v)则返回false,表示途中存在从源点可达的权为负的回路。
!!!之所以需要第三部分的原因,是因为,如果存在从源点可达的权为负的回路。则 应为无法收敛而导致不能求出最短路径。
import java.util.*;
public class ShortestPath {
/**
*
* bellman=ford算法计算从startNode到各个节点的最短距离。如果有负权环则返回null。
* 之所以需要N-1遍,是因为边的顺序是无序的
* 时间复杂度O(VE)
* @param weight
* graph[i][j]表示从i到j有边
* @param startNode
*
* @param N
* 节点数量
* @return
*/
public int[] bellmanFord(int[][] weight,int startNode,int N){
Graph graph = new Graph();
graph.v = N;
graph.e = weight.length;
for(int[] a : weight){
Edge edge = new Edge();
edge.src = a[0];
edge.dest = a[1];
edge.weight = a[2];
graph.edgeList.add(edge);
}
int[] dist = new int[N];//i到startNode的最短距离
Arrays.fill(dist,Integer.MAX_VALUE);
dist[startNode] = 0;
for(int i=1;i<N;i++){
boolean update = false;
for(int j=0;j<graph.e;j++){
Edge edge = graph.edgeList.get(j);
if(dist[edge.src]!=Integer.MAX_VALUE && dist[edge.dest]> dist[edge.src]+edge.weight){
dist[edge.dest] = dist[edge.src]+edge.weight;
update = true;
}
}
if(!update){
break;
}
}
boolean isBack = false;
for(int i=0;i<graph.e;i++){
Edge edge = graph.edgeList.get(i);
if (dist[edge.src]!=Integer.MAX_VALUE && dist[edge.src] + edge.weight<dist[edge.dest]){
isBack = true;
}
}
return isBack?null:dist;
}
public static void main(String[] args){
int[][] weight = new int[9][];
weight[2] = new int[]{0,1,-1};
weight[1] = new int[]{0,2,4};
weight[0] = new int[]{1,2,3};
weight[3] = new int[]{1,3,2};
weight[4] = new int[]{1,4,2};
weight[5] = new int[]{3,2,5};
weight[6] = new int[]{3,1,1};
weight[7] = new int[]{4,3,-3};
weight[8] = new int[]{5,6,2};
int[] dist = new ShortestPath().bellmanFord(weight,0,7);
if(dist!=null){
for(int i=0;i<dist.length;i++){
System.out.print(dist[i]+"\t");
}
}else {
System.out.println("有回路");
}
}
}
class Graph{
int v;
int e;
List<Edge> edgeList = new ArrayList<>();
}
class Edge{
int src;
int dest;
int weight;
}