我想在边缘加权图中为最短路径实现迭代器。
public class Graph<T> implements GraphADT<T> {
protected final int DEFAULT_CAPACITY = 10;
protected int numVertices; // number of vertices in the graph
protected boolean[][] adjMatrix; // adjacency matrix
protected T[] vertices; // values of vertices
protected double weight[][];
我尝试了很多实现,甚至尝试了自己的实现,但我认为我还没有理解Dijkstra算法的逻辑,任何人都可以向我解释或者给他们实现Java的实现
这是我尝试实施
public Iterator<T> iteratorShortestPathW1(int startIndex, int targetIndex) {
ArrayUnorderedList<T> resultList = new ArrayUnorderedList<T>();
if (!indexIsValid(startIndex) || !indexIsValid(targetIndex)) {
return resultList.iterator();
}
Iterator<T> it = iteratorShortestPathW2(startIndex,
targetIndex);
while (it.hasNext()) {
resultList.addToRear(vertices[((Integer) it.next()).intValue()]);
}
return resultList.iterator();
}
public Iterator<T> iteratorShortestPathW(T startVertex, T targetVertex) {
return iteratorShortestPathW1(getIndex(startVertex),
getIndex(targetVertex));
}
protected Iterator<T> iteratorShortestPathW2(int startIndex, int targetIndex) {
int index = startIndex;
int[] tamcaminho = new int[numVertices];
int[] predecessor = new int[numVertices];
LinkedQueue<Integer> traversalQueue = new LinkedQueue<Integer>();
ArrayUnorderedList<Integer> resultList = new ArrayUnorderedList<Integer>();
if (!indexIsValid(startIndex) || !indexIsValid(targetIndex) || (startIndex == targetIndex)) {
return (Iterator<T>) resultList.iterator();
}
boolean[] visited = new boolean[numVertices];
for (int i = 0; i < numVertices; i++) {
visited[i] = false;
}
traversalQueue.enqueue(startIndex);
visited[startIndex] = true;
tamcaminho[startIndex] = 0;
predecessor[startIndex] = -1;
while (!traversalQueue.isEmpty() && (index != targetIndex)) {
System.out.print("acima");
index = traversalQueue.dequeue();
int menor = 999;
for (int i = 0; i < numVertices; i++) {
if (adjMatrix[index][i] && !visited[i]) {
tamcaminho[i] = (int) weight[index][i];
if (menor > tamcaminho[i]) {
menor = tamcaminho[i];
}
}
}
for (int i = 0; i < numVertices ; i++) {
if (tamcaminho[i] == menor) {
System.out.print("abaixo");
visited[index] = true;
traversalQueue.enqueue(i);
predecessor[i] = index;
}
}
}
if (index != targetIndex) {
return (Iterator<T>) resultList.iterator();
}
LinkedStack<Integer> stack = new LinkedStack<Integer>();
index = targetIndex;
stack.push(new Integer(index));
do {
index = predecessor[index];
stack.push(new Integer(index));
} while (index != startIndex);
while (!stack.isEmpty()) {
resultList.addToRear(((Integer) stack.pop()));
}
return (Iterator<T>) resultList.iterator();
}
答案 0 :(得分:0)
来自Cormen算法简介。 Dijkstra算法维护一组顶点S,其最终最短路径 来源的权重已经确定。该算法反复出现 选择具有最小最短路径估计的顶点u 2 V S,添加u 到S,放松离开你的所有边缘。在以下实现中,我们使用a 顶点的最小优先级队列Q,由其d值键入。
DIJKSTRA.G;w; s/
1 INITIALIZE-SINGLE-SOURCE.G; s/
2 S D ;
3 Q D G:V
4 while Q ¤ ;
5 u D EXTRACT-MIN.Q/
6 S D S [ fug
7 for each vertex 2 G:AdjOEu
8 RELAX.u; ;w/DIJKSTRA.G;w; s/