public int Dijkstra(GraphNode<T> start, GraphNode<T> end) {
PriorityQueue<Edge<T>> heap = new PriorityQueue<Edge<T>>(25,new Comparator<Edge<T>>(){
public int compare(Edge<T> first, Edge<T> second) {
return (first.getWeight()+first.getOrigin().getDistance()) - (second.getWeight()+second.getOrigin().getDistance());
}
});
resetDistances();
start.setDistance(0);
GraphNode<T> temp = start;
resetVisited();
do {
LinkedList<Edge<T>> connectors = temp.edgeList;
for(int i = 0; i < connectors.size(); i++) {
Edge<T> edge = connectors.get(i);
if (!edge.getDestination().getVisited()) {
heap.add(edge);
}
}
temp.setVisited(true);
Edge<T> tempEdge = heap.poll();
temp = tempEdge.getDestination();
int distance = temp.distance;
int newDistance = tempEdge.getOrigin().getDistance() + tempEdge.getWeight();
if (newDistance < distance)
temp.setDistance(newDistance);
} while (!heap.isEmpty());
return end.getDistance();
}
private void resetDistances() {
for(int i = 0; i < nodeList.size(); i++)
nodeList.get(i).setDistance(Integer.MAX_VALUE);
}
private void resetVisited() {
for (int i = 0; i < nodeList.size(); i++)
nodeList.get(i).setVisited(false);
}
The above code was tested on a graph with 7 nodes and the distance of the edges never exceeds 20, so it was a relatively small graph. When I put in 0 as my start and 1 or 2 as my end it returns the right number, If I start from anywhere else or end somewhere other than those 2 it returns the number -2147483625 or something very similar. It's kind of confusing me. However, in my resetDistances method if I change the value from Integer.MAX_VALUE to a smaller number like 20,000. The algorithm works when I test from any node to any node. My question is why will it work when I set all the graph nodes distance to 20,000 and not Integer.MAX_VALUE? From all the different articles I have read it seems I am supposed to set the distance to MAX_VALUE so why does it work like this? If you need my graphs or any other files let me know and I will be glad to post them.
This post has been edited by RobW1985: 22 August 2011 - 10:40 AM

New Topic/Question
Reply



MultiQuote






|