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