图的单源最短路径之Bellman Ford算法 java 实现

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;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值