Bellman Ford 算法
简述:遍历所有的边,边有起点i和终点j,如果源点到顶点的最短路径的d[i]已经算出来,就比较d[j]和d[i]+cost,如果前者比较大,则更新d[j]。如此往复,知道某次循环中没有更新的情况
import java.util.Arrays;
=
public class SingleOriginShortestDistanceBellman {
public static void main(String[] args) {
int []shortestPath=shortestPath(0);
System.out.println(Arrays.toString(shortestPath));
}
static int [][] graph=
{
{0,2,5,0,0,0,0},
{2,0,4,6,10,0,0},
{5,4,0,2,0,0,0},
{0,6,2,0,0,1,0},
{0,10,0,0,0,3,5},
{0,0,0,1,3,0,9},
{0,0,0,0,5,9,0},
};
/**
* 求起点到各顶点的最短距离
* @param i
* @return
*/
private static int[] shortestPath(int s) {
int n=graph.length;
//记录s到各个顶点的最短距离
int d[]=new int[n];
for(int i=0;i<n;i++)
d[i]=Integer.MAX_VALUE;//统一初始化为无穷
d[s]=0;//自己到自己的距离为0
while(true)
{
boolean updated=false;
//扫描所有边
for(int i=0;i<n;i++) {
if(d[i]==Integer.MAX_VALUE)
continue;//如果起点到i的最短距离还没有算出来
int cost=0;
for(int j=0;j<n;j++) {
cost=graph[i][j];//i j之间的距离
if(cost>0)
{
if(d[j]>d[i]+cost) {
//起点到直接到j的距离比先到i,i再到j的距离远,则更新
d[j]=d[i]+cost;
updated=true;
}
}
}
}
//没有更新,则退出while循环
if(!updated) break;
}
return d;
}
}