I'm trying to implement Dijkstra algorithm on my own in java. I have a min-priority queue that stores nodes ordered by their current shortest path.
The first step goes smoothly, I set starting node with distance 0 and others with Integer.MAX_VALUE. The starting node was polled out correctly. However, after i removed the first node, the second node that been removed is not the node with smallest distance. I cant figure out why. Any opinions?
Here is my code
public void Dijkstra(Node s){
initialize(s);
List<Node> set = new ArrayList<Node>();
Comparator<Node> c = new CompareNode();
PriorityQueue<Node> Q = new PriorityQueue<Node>(V,c);
for (Node q: Nodes){
Q.add(q);
}
while (Q.size()!=0){
Node u = Q.remove();
System.out.println();
System.out.println(u + " is removed with dis " + u.getD());
set.add(u);
for (Node w: u.getWeightedAdj().keySet()){
relax(u,w);
}
}
}
public void initialize(Node s){
for (Node v: Nodes){
v.setD(Integer.MAX_VALUE);
v.setPredecessor(null);
}
s.setD(0);
}
public void relax(Node u, Node w){
if (w.getD()>u.getD()+u.getWeightedAdj().get(w)){
w.setD(u.getD()+u.getWeightedAdj().get(w));
w.setPredecessor(u);
}
}
And comparator class
import java.util.Comparator;
public class CompareNode implements Comparator<Node> {
@Override
public int compare(Node o1, Node o2) {
if (o1.getD()>o2.getD())
return 1;
if (o1.getD()<o2.getD())
return -1;
return 0;
}
}
when I ran it, the outcome looks like this
A is removed with dis 0
E is removed with dis 2147483647
C is removed with dis 2
D is removed with dis -2147483648
B is removed with dis 3