【发布时间】:2015-04-29 15:36:30
【问题描述】:
我完全不知道该怎么做。我正在尝试对维基百科在 Dijkstra 上的带有优先级队列的伪代码进行编码,但我很难进行调整以适应我需要找到的内容。到目前为止,这是我的(不完整的)代码,非常感谢任何帮助。
public int doDijkstras (String startVertexName, String endVertexName, ArrayList< String > shortestPath) {
PriorityQueue<QEntry> q = new PriorityQueue<QEntry>();
int cost = 0;
int newCost;
QEntry pred = null;
for (String s : this.getVertices()) {
if (!s.equals(startVertexName)) {
cost = Integer.MAX_VALUE;
pred = null;
}
q.add(new QEntry(s, cost, pred, adjacencyMap.get(s)));
}
while (!q.isEmpty()) {
QEntry curr = getMin(q);
for (String s : curr.adj.keySet()) {
newCost = curr.cost + this.getCost(curr.name, s);
QEntry v = this.getVert(q, s);
if (newCost < v.cost) {
v.cost = newCost;
v.pred = curr;
if (!q.contains(curr)) {
q.add(curr);
}
}
}
}
}
private QEntry getMin(PriorityQueue<QEntry> q) {
QEntry min = q.peek();
for (QEntry temp : q) {
if (min.cost > temp.cost) {
min = temp;
}
}
return min;
}
private QEntry getVert(PriorityQueue<QEntry> q, String s) {
for (QEntry temp : q) {
if (temp.name.equals(s)) {
return temp;
}
}
return null;
}
class QEntry {
String name;
int cost;
QEntry pred;
TreeMap<String, Integer> adj;
public QEntry(String name, int cost, QEntry pred, TreeMap<String, Integer> adj) {
this.name = name;
this.cost = cost;
this.adj = adj;
this.pred = pred;
}
}
【问题讨论】:
-
感谢您的编辑,第一篇文章试图弄清楚如何。
-
QEntry curr = getMin(q);--你为什么要对q做这种事?如果您覆盖QEntry#compareTo()方法或使用自定义比较器创建q,您可以通过q.poll()获得最小条目 -
您有什么特别的问题?有什么你不知道如何翻译成 Java 的吗? (什么?)否则,有什么问题?
-
我不知道如何从这一点开始。我该怎么做才能将最短路径添加到给定的 ArrayList 并返回最短路径的成本