遇到的问题都写在注释里面了。
package graph;
/*
* 还是整个原理没记清,前几天看的,今天已经忘记了好多。
* 只是看了一个创建一个数组表示起点到各个顶点的距离这个思想,
* 就自己写出来这个程序,还是比较满意的。
*
* 忘记的原理:
* 1、计算的是起点到各个顶点的距离,所以更新距离那里不应该只计算当前顶点到
* 其他顶点的距离,而是要加上起始顶点到当前顶点的距离。
* 2、更新距离时要比较一下新旧距离的大小,保留最小的那一个。
* 3、获取当前所有距离中最小值的时候,要判断所选顶点是否已经在树中,已经在树中的话
* 即使是最小值也不能选取。因为选取最小值是为了确定下一个访问的结点,如果选取已经在树
* 中的顶点的话,就会重复访问。
*/
class Pvertex{
char label;
boolean isInTree;
public Pvertex(char lab) {
label = lab;
isInTree = false;
}
}
class DisPar{
public int distance;
public int parrentVert;
public DisPar(int d, int pa) {
distance = d;
parrentVert = pa;
}
}
public class path {
int Max_Verts = 20;
int INF = 10000;
Pvertex[] VertList;
int[][] adjMat;
DisPar[] vertArr;
int nVerts;
int nInTree;
int currentVert;
int startVert=0;
public path() {
nVerts = 0;
nInTree = 0;
VertList = new Pvertex[Max_Verts];
vertArr = new DisPar[Max_Verts];
adjMat = new int[Max_Verts][Max_Verts];
for(int i=0; i<Max_Verts; i++) {
for(int j=0; j<Max_Verts; j++) {
adjMat[i][j] = INF;
}
}
}
public void addVert(char lab) {
VertList[nVerts++] = new Pvertex(lab);
}
public void addEdge(int start, int end, int distance) {
adjMat[start][end] = distance;
}
public void sPath() {
currentVert = 0;
VertList[0].isInTree = true;
for(int i=0; i<nVerts; i++) {
int distance = adjMat[0][i];
vertArr[i] = new DisPar(distance, currentVert);
}
while(nInTree<nVerts-1) {
int nextIndex = getMin();
if(vertArr[nextIndex].distance==INF) {
System.out.println("There is no path!");
return;
}
else {
currentVert = nextIndex;
adjustPath();
}
displayPath();
VertList[currentVert].isInTree = true;
nInTree++;
}
}
public int getMin() {
int MinDist = vertArr[0].distance;
int index = 0;
for(int i=1; i<nVerts; i++) {
if(!VertList[i].isInTree) {
int dist = vertArr[i].distance;
if(dist<MinDist) {
MinDist = dist;
index = i;
}
}
}
return index;
}
public void adjustPath() {
int startToCur = vertArr[currentVert].distance;
int curDist;
int oldDist;
int newDist;
for(int i=1; i<nVerts; i++) {
curDist = adjMat[currentVert][i];
oldDist = vertArr[i].distance;
newDist = startToCur + curDist;
if(oldDist>newDist) {
vertArr[i].distance = newDist;
vertArr[i].parrentVert = currentVert;
}
}
}
public void displayPath() {
for(int j=0; j<nVerts; j++) {
System.out.print(VertList[j].label + "=");
if(vertArr[j].distance==INF) {
System.out.print("inf");
}
else {
System.out.print(vertArr[j].distance);
}
System.out.print("(" + VertList[vertArr[j].parrentVert].label
+ ") ");
}
System.out.println();
}
public static void main(String[] args) {
path p = new path();
p.addVert('A');
p.addVert('B');
p.addVert('C');
p.addVert('D');
p.addVert('E');
p.addEdge(0, 1, 50);
p.addEdge(0, 3, 80);
p.addEdge(1, 2, 60);
p.addEdge(1, 3, 90);
p.addEdge(2, 4, 40);
p.addEdge(3, 2, 20);
p.addEdge(3, 4, 70);
p.addEdge(4, 1, 50);
p.sPath();
//int INF=100;
//System.out.print(100!=INF);
}
}
结果: