My implementation for directed graph works fine. It's a "lazy" version because it uses simple priority queues instead of indexed ones. I changed the code to get a solution for undirected graphs but it doesn't work. dijkstra(int s)
is a method of a class Graph
. The implementation of Graph
is based on a list of adjacencies. The entire code is based on the explanations of Sedgewick's book.
public void dijkstra(int s) {
marked = new boolean[V];
distTo = new int[V];
edgeTo = new Edge[V];
Comparator<Edge> comparator = new Comparator<Edge>() {
public int compare(Edge e1, Edge e2) {
int dist1 = distTo[e1.either()] + e1.weight();
int dist2 = distTo[e2.either()] + e2.weight();
if (dist1 < dist2) {
return -1;
} else if (dist1 > dist2) {
return 1;
} else {
return 0;
}
}
};
pq = new PriorityQueue<Edge>(comparator);
for (int v = 0; v < V; ++v) {
distTo[v] = Integer.MAX_VALUE;
}
distTo[s] = 0;
relax(s);
while (!pq.isEmpty()) {
Edge e = pq.poll();
int v = e.either();
int w = e.other(v);
if (!marked[w]) {
relax(w);
}
}
}
private void relax(int v) {
marked[v] = true;
for (Edge e : adj[v]) {
int w = e.other(v);
if (distTo[w] > distTo[v] + e.weight()) {
distTo[w] = distTo[v] + e.weight();
edgeTo[w] = e;
pq.add(e);
}
}
}