1)、胜利乡有7个村庄(A, B, C, D, E, F, G)
2)、各个村庄的距离用边线表示(权) ,比如 A – B 距离 5公里
3)、问:如何计算出各村庄到 其它各村庄的最短距离?
package Floyd;
import java.util.Arrays;
public class FloydAlgorithm {
public static void main(String[] args) {
char[] vertex = {'A','B','C','D','E','F','G'};
int[][] matrix = new int[vertex.length][vertex.length];
final int N = 65536;
matrix[0] = new int[] { 0, 5, 7, N, N, N, 2 };
matrix[1] = new int[] { 5, 0, N, 9, N, N, 3 };
matrix[2] = new int[] { 7, N, 0, N, 8, N, N };
matrix[3] = new int[] { N, 9, N, 0, N, 4, N };
matrix[4] = new int[] { N, N, 8, N, 0, 5, 4 };
matrix[5] = new int[] { N, N, N, 4, 5, 0, 6 };
matrix[6] = new int[] { 2, 3, N, N, 4, 6, 0 };
Graph graph = new Graph(vertex.length, vertex, matrix);
graph.flyod();
graph.show();
}
}
//新建一个图
class Graph {
private char[] vertex;//顶点数组
private int[][] dis;//距离数组
private int[][] pre;//前驱结点
public Graph(int length,char[] vertex,int[][] matrix) {
this.vertex = vertex;
this.dis=matrix;
this.pre = new int[length][length];
//初始化pre数组
for(int i = 0 ; i < length;i++) {
Arrays.fill(pre[i], i);
}
}
// 显示pre数组和dis数组
public void show() {
//为了显示便于阅读,我们优化一下输出
char[] vertex = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
for (int k = 0; k < dis.length; k++) {
// 先将pre数组输出的一行
for (int i = 0; i < dis.length; i++) {
System.out.print(vertex[pre[k][i]] + " ");
}
System.out.println();
// 输出dis数组的一行数据
for (int i = 0; i < dis.length; i++) {
System.out.print("("+vertex[k]+"到"+vertex[i]+"的最短路径是" + dis[k][i] + ") ");
}
System.out.println();
System.out.println();
}
}
public void flyod() {
int len = 0;
//中间结点开始遍历,中间顶点 [A, B, C, D, E, F, G]
for(int k = 0 ; k < vertex.length;k++) {
//出发顶点开始遍历,出发顶点 [A, B, C, D, E, F, G]
for(int i = 0 ; i < vertex.length;i++) {
//终点开始遍历,终点[A, B, C, D, E, F, G]
for(int j = 0 ; j < vertex.length;j++) {
len = dis[i][k]+dis[k][j];
//如果len小于i到j的直接距离
if(len<dis[i][j]) {
//更新dis和pre
dis[i][j] = len;
pre[i][j]=pre[k][j];
}
}
}
}
}
}
for(int k = 0 ; k < vertex.length;k++) {
//出发顶点开始遍历,出发顶点 [A, B, C, D, E, F, G]
for(int i = 0 ; i < vertex.length;i++) {
//终点开始遍历,终点[A, B, C, D, E, F, G]
for(int j = 0 ; j < vertex.length;j++) {
len = dis[i][k]+dis[k][j];
//如果len小于i到j的直接距离
if(len<dis[i][j]) {
//更新dis和pre
dis[i][j] = len;
pre[i][j]=pre[k][j];
}
}
}
}
弗洛伊德算法的中心思想就是通过三层循环先固定中间结点k,再固定开始结点i,然后遍历终点j找到从i到j的最小值,若找到则更新dis和pre表