這段代碼用於實現Dijkstra的未加權圖的算法。我應該改變什麼來使用加權圖?我的圖的邊緣是雙值,有沒有機會在shortestPath方法中使用泛型類型?如何使Dijkstra的算法適用於加權圖
/**
* Determine the shortest path to all vertices from a vertex using Dijkstra's algorithm
* To be called by public short method
*
* @param graph Graph object
* @param sourceIdx Source vertex
* @param knownVertices previously discovered vertices
* @param verticesIndex index of vertices in the minimum path
* @param minDist minimum distances in the path
*
*/
private static <V> void shortestPath(AdjacencyMatrixGraph<V,Double> graph, int sourceIdx, boolean[] knownVertices, int[] verticesIndex, double [] minDist) {
V vertexOrig = graph.vertices.get(sourceIdx);
Queue<V> qaux = new LinkedList<V>();
for(int i = 0; i < graph.numVertices; i++) {
minDist[i] = 0;
verticesIndex[i] = -1;
}
qaux.add(vertexOrig);
while(!qaux.isEmpty()) {
V vertex = qaux.remove();
for (V vertexAdj: graph.directConnections(vertex)) {
if(minDist[graph.toIndex(vertexAdj)] == 0) {
minDist[graph.toIndex(vertexAdj)] = minDist[graph.toIndex(vertex)]
+ graph.getEdge(vertex, vertexAdj);
verticesIndex[graph.toIndex(vertexAdj)] = graph.toIndex(vertex);
qaux.add(vertexAdj);
}
}
}
}
/**
* Determine the shortest path between two vertices using Dijkstra's algorithm
*
* @param graph Graph object
* @param source Source vertex
* @param dest Destination vertices
* @param path Returns the vertices in the path (empty if no path)
* @return minimum distance, -1 if vertices not in graph or no path
*
*/
public static <V> double shortestPath(AdjacencyMatrixGraph<V, Double> graph, V source, V dest, LinkedList<V> path){
path.clear();
if(!graph.checkVertex(source) || !graph.checkVertex(dest)) return -1;
else if(source.equals(dest)) {
path.add(dest);
return 0;
}
double minDist[] = new double[graph.numVertices];
int verticesIndex[] = new int[graph.numVertices];
shortestPath(graph, graph.toIndex(source), new boolean[graph.numVertices]
, verticesIndex, minDist);
if(verticesIndex[graph.toIndex(source)] == -1 || verticesIndex[graph.toIndex(dest)] == -1) return -1;
recreatePath(graph, graph.toIndex(source), graph.toIndex(dest), verticesIndex, path);
Collections.reverse(path);
System.out.println(path);
System.out.println(minDist[graph.toIndex(dest)]);
return minDist[graph.toIndex(dest)];
}
/**
* Recreates the minimum path between two vertex, from the result of Dikstra's algorithm
*
* @param graph Graph object
* @param sourceIdx Source vertex
* @param destIdx Destination vertices
* @param verticesIndex index of vertices in the minimum path
* @param Queue Vertices in the path (empty if no path)
*/
private static <V> void recreatePath(AdjacencyMatrixGraph<V, Double> graph, int sourceIdx, int destIdx, int[] verticesIndex, LinkedList<V> path){
path.add(graph.vertices.get(destIdx));
if (sourceIdx != destIdx){
destIdx = verticesIndex[destIdx];
recreatePath(graph, sourceIdx, destIdx, verticesIndex, path);
}
}
Dijkstra的算法適用於加權圖。如果這個實現不能這樣做,那不是Dijkstra算法的實現。 – kraskevich