单源最短路算法—Bellman-Ford

Bellman-Ford 算法是一种用于计算带权有向图中单源最短路径(SSSP:Single-Source Shortest Path)的算法。该算法由 Richard Bellman 和 Lester Ford 分别发表于 1958 年和 1956 年,而实际上 Edward F. Moore 也在 1957 年发布了相同的算法,因此,此算法也常被称为 Bellman-Ford-Moore 算法。

代码如下:

package Test1;

import java.util.Scanner;
/*
 7 10
0 1 2
0 2 5
1 2 4
1 3 6
1 4 10
2 3 2
3 5 1
5 4 3
4 6 5
5 6 9
 */
public class L11 {

	static int V, E;
	static int INF = 10000;//一个足够大的常数
	static Edge[] es = new Edge[100];// 边
	static int[] d = new int[100];// 最短距离
	// 求解从顶点s出发到所有顶点的最短距离

	static void short_path(int s) {
		for (int i = 0; i < V; i++) {
			d[i] = INF;
		}
		d[s] = 0;
		while (true) {
			boolean update = false;
			for (int i = 0; i < E; i++) {
				Edge e = es[i];
				//从s点开始,                      如果从s到to的距离比从s到from的距离加上cost还大,那么就用后面的距离
				if (d[e.from] != INF && d[e.to] > d[e.from] + e.cost) {
					d[e.to] = d[e.from] + e.cost;
					update = true;
				}
			}
			if (!update)
				break;
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner sc = new Scanner(System.in);
		V = sc.nextInt();
		E = sc.nextInt();
		for (int i = 0; i < 100; i++) {
			es[i] = new Edge();
		}
		for (int i = 0; i < E; i++) {
			es[i].from=sc.nextInt();
			es[i].to=sc.nextInt();
			es[i].cost=sc.nextInt();
		}
		short_path(0);
		System.out.println(d[0]);
		System.out.println(d[1]);
		System.out.println(d[2]);
		System.out.println(d[3]);
		System.out.println(d[4]);
		System.out.println(d[5]);
		System.out.println(d[6]);
	}

}

class Edge {
	int from, to;// 从顶点from指向顶点to
	int cost;// 权值为cost
}

判断图中是否存在负圈的代码:

	static boolean find_negative_loop() {
		for (int i = 0; i < d.length; i++) {
			d[i] = 0;
		}
		for (int i = 0; i < V; i++) {
			for (int j = 0; j < E; j++) {
				Edge e = es[j];
				if (d[e.to] > d[e.from] + e.cost) {
					d[e.to] = d[e.from] + e.cost;

					// 如果第n次仍然更新了,则存在负圈
					if (i == V - 1)
						return true;
				}
			}
		}
		return false;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值