明确:
弗洛伊德算法和地杰斯特拉算法,都是解决最短路径问题,但是,弗洛伊德:用户传入一个点,找出这个点到其他店的最短路径。副楼伊的是求所有点。
代码:
public class Graph {
char[] vertexs;
int [][]dis; //保存,从各个顶点出发到其他顶点的距离,以及最后的结果,保存在这里
int[][] pre; //保存到达目标顶点的前驱结点
public Graph(int length,char[] vertexs, int[][] matrtix) {
this.vertexs = vertexs;
this.dis = matrtix;
this.pre = new int[length][length];
//初始化pre数组,此数组存放的是前驱结点的下标
for (int i = 0; i < length; i++) {
Arrays.fill(pre[i], i);
//刚开始前驱都是自己
}
}
//遍历
public void show(){
for(int []a:dis){
for(int data:a){
System.out.printf("%4d",data);
}
System.out.println();
}
}
//弗洛伊德算法
public void floyd(){
int len=0; //变量保存距离
//对中间顶点遍历,k就是中间定点的下标
for(int k=0;k
package com;
public class floydDemo {
static final int N=99;
public static void main(String[] args) {
char []vertexs={'A','B','C','D','E','F','G'};
int martix[][]={
{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(vertexs.length,vertexs,martix);
graph.floyd();
graph.showEnd();
}
}