标签:最短路 图片 static 代码实现 super count 多源 顶点 str
举例
更一般的,继续并入下一个中转顶点一直到 vexCount 个时,arcs[i][j] 的结果保存的就是整个图中两点之间的最短路径了 // DP!
public class FloydAlgorithm {
public static void main(String[] args) {
char[] vertexs = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
int[][] matrix = new int[vertexs.length][vertexs.length];
final int N = 65535; // 表示不可以连接
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(vertexs, matrix);
graph.show();
graph.floyd();
System.out.println();
graph.show();
}
}
class Graph {
int vCount;
char[] vertexs;
int[][] dis; // 保存距离
int[][] pre; // 保存前驱
public Graph(char[] vertexs, int[][] dis) {
super();
vCount = vertexs.length;
this.vertexs = vertexs;
this.dis = dis;
this.pre = new int[vCount][vCount];
for(int i = 0; i < vCount; i++)
for(int j = 0; j < vCount; j++)
pre[i][j] = i;
}
public void floyd() {
int len;
for(int k = 0; k < vCount; k++) // k: 中间顶点
for(int i = 0; i < vCount; i++) // i: 出发顶点
for(int j = 0; j < vCount; j++) { // j: 终点
len = dis[i][k] + dis[k][j];
if(dis[i][j] > len) {
dis[i][j] = len;
pre[i][j] = k;
}
}
}
public void show() {
System.out.print(" ");
for(int i = 0; i < vCount; i++)
System.out.printf("%8c ", vertexs[i]);
System.out.println();
for(int i = 0; i < vCount; i++) {
System.out.print(vertexs[i]+" ");
for(int j = 0; j < vCount; j++)
System.out.printf("%c(%5d) ", vertexs[pre[i][j]], dis[i][j]);
System.out.println();
}
}
}
标签:最短路 图片 static 代码实现 super count 多源 顶点 str
原文地址:https://www.cnblogs.com/liujiaqi1101/p/12489977.html