【发布时间】:2016-12-16 23:03:49
【问题描述】:
我想为我的边加权图中的最短路径实现一个迭代器。
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();
}
【问题讨论】:
-
分享你自己的实现,你可能会在你的具体问题上得到一些帮助。
-
@Atreys 我添加了我的实施尝试
标签: algorithm double dijkstra protected