问题:
求出每个顶点到其他顶点的距离
Graph.java
import java.util.Arrays;
public class Graph {
int[][] dis; //距离表
int[][] pre; //前驱表
char[] vertex; //顶点数组
public Graph(int[][] dis, char[] vertex) {
super();
this.dis = dis;
this.vertex = vertex;
this.pre = new int[vertex.length][vertex.length];
for (int i = 0; i < vertex.length; i++) {
Arrays.fill(pre[i], i);
}
}
public void show() {
System.out.println("距离表");
for (int i = 0; i < dis.length; i++) {
for (int j = 0; j < dis.length; j++) {
System.out.printf("%6s->%s[%4d]", vertex[i], vertex[j], dis[i][j]);
}
System.out.println();
}
System.out.println(
"----------------------------------------------------------------------------------------------------------------------");
System.out.println("前驱表");
for (int i = 0; i < dis.length; i++) {
for (int j = 0; j < dis.length; j++) {
System.out.printf("%6s->%s (%s)", vertex[i], vertex[j],vertex[pre[i][j]]);
}
System.out.println();
}
}
//弗洛伊德算法
public void floyd() {
int len;
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];
}
}
}
}
}
}
Text.java
public class Text {
public static void main(String[] args) {
char[] vertex= {'A','B','C','D','E','F','G'};
final int n=1000;
int[][] dis= {{0,5,7,n,n,n,2},
{5,0,n,9,n,n,3},
{7,n,0,n,8,n,n},
{n,9,n,0,n,4,n},
{n,n,8,n,0,5,4},
{n,n,n,4,5,0,6},
{2,3,n,n,4,6,0}};
Graph graph = new Graph(dis, vertex);
graph.floyd();
graph.show();
}
}