每一对顶点之间的最短路径(floyd算法)

Floyd算法仍从图的带权邻接矩阵出发。算法的主要思想是:

首先定义原图的矩阵为D(-1)         。即:

D(-1)[i][j] = G.arcs[i][j];

D(K)[i][j] = Min{D(k-1)[i][j] , D(k-1)[i][k] + D(k-1)[k][j] }

 

 

package test09;

public class Floyd {
	private int[][] adjMat;
	private static final int INFINITY = ~(1<<31);
	
	public Floyd(int size) {
		adjMat = new int[size][size];
		for(int i=0; i<size; i++)
			for(int j=0; j<size; j++)
				adjMat[i][j] = INFINITY;
	}

	void connect(int from, int to, int length) {
		adjMat[from][to] = length;
	}

	void floyd() { //floyd算法
		for(int y=0; y<adjMat.length; y++) 
			for(int x=0; x<adjMat.length; x++) 
				if(adjMat[y][x] != INFINITY)	
					for(int z=0; z<adjMat.length; z++)
						if(adjMat[z][y] != INFINITY) {
							int newLength = adjMat[z][y] + adjMat[y][x];
							adjMat[z][x] = newLength < adjMat[z][x] ? newLength : adjMat[z][x];	
						}
		
	}

	int[][] getConnections() {
		return adjMat;
	}

	public static void main(String[] args) {
		Floyd w = new Floyd(3);
		w.connect(0, 0, 0);
		w.connect(0, 1, 4);
		w.connect(0, 2, 11);
		w.connect(1,0,6);
		w.connect(1,1,0);
		w.connect(1,2,2);
		w.connect(2,0,3);
		w.connect(2,2,0);
		for(int[] a: w.getConnections()) {
			for(int i: a) System.out.print((i == INFINITY? "INF" : i) + "\t");
			System.out.println();
		}
		w.floyd();
		System.out.println("==================");
		for(int[] a: w.getConnections()) {
			for(int i: a) System.out.print((i == INFINITY? "INF" : i) + "\t");
			System.out.println();
		}
	}

}

 

执行结果为:

0 4 11

6 0 2

3 INF 0

==================

0 4 6

5 0 2

3 7 0

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值