나는 인접 행렬로 작업 중이며 그래프 내에서 최단 경로를 찾는 함수를 작성하려고합니다. 최소 스패닝 트리 함수를 작성하는 데 사용한 Prim 알고리즘을 수정하려고합니다.Java에서 최단 경로 구현
public static int shortest(int first, int last) throws Exception{
int weight[] = new int[Nodes.length]; //keeps track of the weights of the added edges
int path[] = new int[Nodes.length]; //keeps track of the nodes in the path
boolean visited[] = new boolean[Nodes.length]; //keeps track of nodes visited
int current;
int total;
int minWeight;
int nodes = Nodes.length;
int i;
for (i=0;i<nodes;i++){ //initialization
path[i]=0;
visited[i]=false;
weight[i]=32767; //largest short int
}
current=first;
weight[current]=0;
total=1;
visited[current]=true;
path[0]=current;
while(total!=nodes){
for(i=1;i<nodes;i++){
if(AMatrix[current][i] != 0 && visited[i]==false && weight[i]>AMatrix[current][i]){
weight[i]=AMatrix[current][i];
path[i]=current;
}
}
minWeight=32767;
for(i=1;i<nodes;i++){
if(visited[i]==false && weight[i]<minWeight){
minWeight=weight[i];
current=i;
}
}
write("current = "+ current);
visited[current]=true;
total++;
if(current == last){
path[total-1]=current;
for(i=1;i<total;i++){
write("includes the node "+Nodes[path[i]]);
}
minWeight=0;
int j=1;
for(i=2;i<total;i++){
write("The weight from "+Nodes[path[j]]+" to "+Nodes[path[i]]+" is "+AMatrix[path[j]][path[i]]);
minWeight = minWeight+AMatrix[path[j]][path[i]];
write("min weight= "+minWeight);
j++;
}
return minWeight;
}
}
return -1;
}
는 내가 첫 번째 노드에서 시작 어디 준 입력 중 하나와 함께 작동하지만 다른 노드에서 시작하려고하면, 실제로는 연결되지 않은 두 개의 노드를 연결하는 경로를 만듭니다. 나는 이것을 오랫동안 보았고, 왜 그렇게하는지 보지 못합니다. 최소한의 스패닝 트리가 훌륭하게 작동하며, 이것이 간단한 수정 일 것이라고 생각했지만 작동하지 않습니다.
실제로이 점에는 많은 문제가 있다고 생각합니다. 예를 들어, 0에서 경로 배열을 시작하는 요소를 인쇄하려고하면 첫 번째 요소가 두 번 인쇄 될 것이므로, 나는 많은 실수를했지만, 그것은 지금 당장 나에게 뻔뻔스럽게 드러난다.
AMatrix는 내 인접 행렬이고 Nodes는 각 노드의 행렬입니다. 쓰기는 출력 파일에 쓰는 기능입니다.
[코드 디버깅으로 문제의 범위를 좁히십시오.] (http://codingkilledthecat.wordpress.com/2012/06/26/how-to-ask-for-programming-help/). 이 프로세스는 스스로 버그를 찾는 데 도움이됩니다. 너가 그것을 좁히기 후에 아직도 그것을 발견 할 수 없으면, 다른 사람은 너를 매우 더 쉽게 원조 할 수 있는다. – Domi