【发布时间】:2013-11-14 20:39:13
【问题描述】:
我的以下代码对于有向图非常有效,当给定无向图时,它不会返回最短路径。
public void Djikstra(int s){
boolean[] marked = new boolean[V];
dist = new double[V];
for(int i = 0; i<V; i++){ # initializing array
dist[i] = Double.POSITIVE_INFINITY;
}
dist[s] = 0.0;
Queue<Integer> pqs = new PriorityQueue<Integer>();
pqs.add(s);
while(!pqs.isEmpty()){
int v = pqs.poll();
if(marked[v]) continue;
marked[v] = true;
for(Edge e : get_list(v)){ # get_list(v) will return an iterable from the adjacency list at index v
v = e.getV()
int w = e.getW();
if(dist[w] > dist[v] + e.getWeight()){
dist[w] = dist[v] + e.getWeight();
distances[w] = e #all the distances will be stored in this array
pqs.add(w);
}
}
}
}
我不确定我的错误是什么?我有点确定这是一个简单的错误,一些提示可以解决问题。
谢谢。
编辑:
public void addEdge(Edge e){
adj[e.getV()].add(e);
adj[e.getW()].add(e);
}
【问题讨论】:
-
对于无向图,您必须考虑边 A -> B 和 B -> A,因此如果适用于有向情况,请确保包含它们并再次运行算法,它应该可以添加剩余的边缘
-
我在我的问题中添加了 addEdge 方法,请检查一下。我已经在这两种情况下都添加了优势。
标签: java graph dijkstra shortest-path