我在实现DijkstraAlgorithm方面遇到了问题。我的代码如下
class DijkstraAlgorithmSet {
private int distances[];
private java.util.Set<Integer> settled;
private java.util.Set<Integer> unsettled;
private int number_of_nodes;
int source = 0;
int min;
int node = 0;
public DijkstraAlgorithmSet(int number_of_nodes) {
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes];
settled = new java.util.HashSet<>();
unsettled = new java.util.HashSet<>();
}
List<Integer> evaluationNodeList = new ArrayList();
List<Integer> destinationNodeList = new ArrayList();
public void dijkstra_algorithm() {
int i, j;
int evaluationNode;
int distance = Integer.MAX_VALUE;
for (int k = 0; k < number_of_nodes; k++) {
distances[k] = Integer.MAX_VALUE;
}
unsettled.add(source);
distances[source] = 0;
while (!unsettled.isEmpty()) {
evaluationNode = getNodeWithMinimumDistanceFromUnsettled();
unsettled.remove(evaluationNode);
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
evaluationNodeList.add(number_of_nodes - 1);
Iterator<Integer> iterator = settled.iterator();
while (iterator.hasNext()) {
Integer next = iterator.next();
}
}
private int getNodeWithMinimumDistanceFromUnsettled() {
Iterator<Integer> iterator = unsettled.iterator();
node = iterator.next();
min = distances[node];
System.out.println("minimum>>>>" + min);
for (int i = 1; i <= distances.length; i++) {
if (unsettled.contains(i)) {
if (distances[i] <= min) {
min = distances[i];
node = i;
}
}
}
System.out.println("min>>>>" + min);
return node;
}
List<Integer> list=new ArrayList<>();
private void evaluateNeighbours(int evaluationNode) {
int edgeDistance = -1;
int newDistance = -1;
int destinationNode;
int temp = 0;
for (destinationNode = 0; destinationNode < number_of_nodes; destinationNode++) {
if (!settled.contains(destinationNode)) {
if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE) {
edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
if (newDistance < distances[destinationNode]) {
distances[destinationNode] = newDistance;
System.out.println("temp>>>>>" + evaluationNode);
temp = evaluationNode;
System.out.println("destinationNode>>>>>" + destinationNode);
}
unsettled.add(destinationNode);
}
}
}
}
我想跟踪路径。但我还没有找到路径。我使用上面的代码只获得了最终距离。
答案 0 :(得分:0)
您可以修改算法,以便在最短路径中的每个节点中存储前导节点。 这种方式在算法完成后,您可以按照前任到原点并重建路径。
换句话说,有另一个数组private int predecessors[];
,并记住最佳距离的来源:
if (newDistance < distances[destinationNode]) {
distances[destinationNode] = newDistance;
predecessors[destinationNode] = evaluationNode;
...
}