我試圖在加權(quán)鄰接矩陣中運(yùn)行 Dijkstra 算法后打印最短路徑。嘗試打印路徑時(shí)出現(xiàn) stackoverflow 錯(cuò)誤。我已經(jīng)嘗試將起始節(jié)點(diǎn)更改為 long 和 BigInteger 類(lèi)型,正如該平臺(tái)上之前的答案所建議的那樣,我也知道我正在使用遞歸方法來(lái)解決該問(wèn)題。import java.util.*;public class djikstra {private static final int invalid = -1;public djikstra(int matrix[][],int start) { int numVertices = matrix[0].length; int [] distances = new int [numVertices]; boolean [] isAdded = new boolean[numVertices]; for (int i=0;i<numVertices;i++) { distances[i]= Integer.MAX_VALUE; isAdded[i] = false; } distances[(int) start]=0; int [] parents = new int [numVertices]; parents[start] = invalid; for(int i=1;i<numVertices;i++) { int closestNeighbour = -1; int shortDist = Integer.MAX_VALUE; for(int j=0; j <numVertices;j++) { if(!isAdded[j] && distances[j]<shortDist) { closestNeighbour = j; shortDist = distances[j]; } } isAdded[closestNeighbour]=true; for(int j = 0; j <numVertices;j++) { int edgeDist = matrix[closestNeighbour][j]; if(edgeDist > 0 && ((closestNeighbour+edgeDist)<distances[j])) { parents[j] = closestNeighbour; distances[j] = shortDist + edgeDist; } }} printSol(start,distances,parents); }private static void printSol(int start,int[] distances,int[] parents) { int numVertices=distances.length; for(int i=0;i<numVertices;i++) { if(i !=start) { path(i,parents); } }}private static void path(int curr,int[]parents) { if(curr== -1) { return; } path(parents[curr],parents);}}}
1 回答

瀟瀟雨雨
TA貢獻(xiàn)1833條經(jīng)驗(yàn) 獲得超4個(gè)贊
這StackOverflowError
是由方法中的無(wú)限遞歸觸發(fā)的path
。 parents[curr]
永遠(yuǎn)不會(huì)保持-1(基本情況),因此遞歸永遠(yuǎn)不會(huì)停止。您需要確保最終path
以 -1 調(diào)用curr
。
添加回答
舉報(bào)
0/150
提交
取消