前两篇只有算法部分,现在附上完整代码
public class ShortPath {
public static void main(String[] args) {
MGraph mg=new MGraph();
mg.addVertex('A');
mg.addVertex('B');
mg.addVertex('C');
mg.addVertex('D');
mg.addVertex('E');
mg.addVertex('F');
mg.addVertex('G');
mg.addVertex('H');
mg.addVertex('I');
mg.addEdge(0,1,1);
mg.addEdge(0,2,5);
mg.addEdge(1,2,3);
mg.addEdge(1,3,7);
mg.addEdge(1,4,5);
mg.addEdge(2,4,1);
mg.addEdge(2,5,7);
mg.addEdge(3,4,2);
mg.addEdge(3,6,3);
mg.addEdge(4,5,3);
mg.addEdge(4,6,6);
mg.addEdge(4,7,9);
mg.addEdge(5,7,5);
mg.addEdge(6,8,7);
mg.addEdge(6,7,2);
mg.addEdge(7,8,4);
//mg.displayAdjMatr();
//int shortPath[]=new int[MGraph.MAXVEX]; //保存最短路径
//int parent[]=new int[MGraph.MAXVEX]; //保存前驱结点下标 parent[i]=k,表示结点i的前驱结点为k,即最短路径中k的下一个点为j
//mg.shortPath_Dijkstra(0, shortPath, parent);
int PathMatrix[][]=new int[MGraph.MAXVEX][MGraph.MAXVEX];
int ShortPathTable[][]=new int[MGraph.MAXVEX][MGraph.MAXVEX];
mg.shortPath_Floyd(PathMatrix, ShortPathTable);
}
}
class MGraph{
public static final int MAXVEX=10;
char vertexList[]; //结点数组
int adjMatr[][]; //邻接矩阵
int nVert; //结点个数
public MGraph(){
vertexList=new char[MAXVEX];
adjMatr=new int[MAXVEX][MAXVEX];
nVert=0;
for(int i=0;i
PathMatrix[i][k]+PathMatrix[k][j]){ //如果经过下标为k的顶点的路径比原来两点间路径更短,修改两点间权值
PathMatrix[i][j]=PathMatrix[i][k]+PathMatrix[k][j];
ShortPathTable[i][j]=k; //路径设置为经过下标为k的顶点
}
}
}
}
for(int i=0;i