前文:迪杰斯特拉算法 单击前往
package FloydAlgorithm;
import java.util.Arrays;
public class Floyd {
public static void main(String[] args) {
char[] vertex = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
int[][] arr = new int[vertex.length][vertex.length];
final int N = 100;
arr[0] = new int[] { 0, 5, 7, N, N, N, 2 };
arr[1] = new int[] { 5, 0, N, 9, N, N, 3 };
arr[2] = new int[] { 7, N, 0, N, 8, N, N };
arr[3] = new int[] { N, 9, N, 0, N, 4, N };
arr[4] = new int[] { N, N, 8, N, 0, 5, 4 };
arr[5] = new int[] { N, N, N, 4, 5, 0, 6 };
arr[6] = new int[] { 2, 3, N, N, 4, 6, 0 };
Graph gp = new Graph(vertex, arr, vertex.length);
gp.floyd();
gp.show();
}
}
//创建图
class Graph {
private char[] vertex;
private int[][] dis; // 从顶点出发到其他节点的距离
private int[][] pre; // 目标节点的前驱节点
// 顶点数组 邻接矩阵 长度大小
public Graph(char[] vertex, int[][] dis, int len) {
this.vertex = vertex;
this.dis = dis;
this.pre = new int[len][len];
// 对pre数组进行初始化
for (int i = 0; i < len; i++) {
Arrays.fill(pre[i], i);
}
}
public void show() {
char[] vertex = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
for (int i = 0; i < dis.length; i++) {
for (int j = 0; j < dis.length; j++) {
System.out.print(vertex[pre[i][j]] + " ");
}
System.out.println();
for (int j = 0; j < dis.length; j++) {
System.out.print("( " + vertex[i] + " -> " + vertex[j] + " 的最短路径 " + dis[i][j] + " ) ");
}
System.out.println();
}
}
// 弗洛伊德算法
public void floyd() {
int len = 0;
// 从中间节点进行遍历
for (int k = 0; k < dis.length; k++) {
// 对出发节点进行遍历
for (int i = 0; i < dis.length; i++) {
// 遍历终点节点
for (int j = 0; j < dis.length; j++) {
len = dis[i][k] + dis[k][j];
if (len < dis[i][j]) {
dis[i][j] = len;
pre[i][j] = pre[k][j];
}
}
}
}
}
}