Using java programming language, I am trying to implement the most efficient shortest path algorithm on a graph with positive edge cost. To the best of my knowledge, that would be Dijkstra's algorithm with a Fibonacci Heap as the priority Queue. I borrowed the following Fibonacci Heap implementation by Keith Schwarz as stated in the link. http://keithschwarz.com/interesting/code/?dir=fibonacci-heap
In my code, I also modified the dijkstra algorithm implementation presented in this question,
Java: Using a Fibonacci Heap for Implementing Dijkstra's Algorithm
Here's my updated dijkstra based on my implementation,
public static void SPFibonacciHeap() {
{
FibonacciHeap<Node> myHeap = new FibonacciHeap<Node>();
//adding all nodes to the PQ (heap)
for(int i=0; i<nodeList.size(); i++)
myHeap.enqueue(nodeList.get(i), nodeList.get(i).d);
while (!myHeap.isEmpty()) {
//deque the minimum (first iteration will be the source)
Entry<Node> u = myHeap.dequeueMin();
// Visit each edge connected from u
for (AdjacentNode a : u.getValue().adjacents) {
//getting the adjacent node
Node v = a.node;
Entry<Node> vEntry = new Entry<Node>(v,v.d);//WRONG
//getting the edge weight
double weight = a.cost;
double distanceThroughU = u.getValue().d + weight;
if (distanceThroughU < v.d) {
v.d = distanceThroughU;
myHeap.decreaseKey(vEntry, v.d); //SHOWS ERROR
v.parent = u.getValue();
}
}
}
}
}
Here's my Node, and AdjacentNode classes,
class Node{
Double [] label;
double d; //node cost
ArrayList<AdjacentNode> adjacents;
Node parent;
public Node(Double[] label, double d,ArrayList<AdjacentNode> adjacents)
{
this.label= label;
this.d=d;
this.adjacents=adjacents;
parent=null;
}
}
class AdjacentNode
{
Node node;
double cost;
public AdjacentNode(Node node, double cost)
{
this.node= node;
this.cost=cost;
}
}
Everything went fine until i wanted to decrease the key in the following line,
myHeap.decreaseKey(vEntry, v.d);
The problem I am facing is that vEntry
should be an already existing node in the heap. However, I am not able to retrieve this node from the heap, since the only way I can think about to retrieve the adjacent node v
is by using the adjacents list in the node u
. But then, I incorrectly represent it as a new Entry Node in the following line,
Entry<Node> vEntry = new Entry<Node>(v,v.d);
This however would create a new Entry holding the node I am looking for, not the entry that exists in the heap with the node I am looking for. This results in Null pointer exception as expected.
I am not able to figure out the solution to this problem. Is it that getting a node entry which is adjacent to a given node entry seems not possible for this heap implementation? Can someone help? Thank you.