I am implementing Dijkstra's algorithm using a heap data structure. I also use an array that keeps track of the "probable minimum distances" of the nodes. The problem is when I am updating the array, how to update the corresponding values in the heap?
ok here's the code
typedef struct temp
{
int nodeTag;
int weight;
struct temp *next;
}myStruct; //this structure corresponds to the elements of the linked list
typedef struct temp *link;
typedef struct
{
int nodeTag; //each node has an integer nodeTag associated with it
link l;
}head; //the head of the elements of the adjacency list
typedef struct {
head *adjList;
int numNodes;
int numEdges;
} Graph;
typedef struct {
int possibleMinWeight;
int minFound; //minFound==1 if true min is found
} dummy;
dummy *dijkstraSSSP(Graph G, int nodeTag)
{
minHeap H=createEmptyHeap(G.numNodes);
while(i=0;i<G.numNodes;i++)
{
if(i!=nodeTag)
H.A[i].priority=INFINITY;
else
H.A[i].priority=0;
H.A[i].nodeTag=i;
}
convertIntoHeap(H);
int min;
dummy *A=(dummy *)malloc(sizeof(int)*G.numNodes);
A[nodeTag-1].possibleMinWeight=0;
A[nodeTag-1].minFound=1;
while(!isEmpty(H))
{
element e=findMin(H); H=deleteMin(H);
A[e.nodeTag-1].minFound=1;
link l=G.adjList[e.nodeTag-1].l;
while(l!=NULL)
{
if(A[l->nodeTag-1].minFound==0); //its true minimum distance is yet to be found
{
if(A[l->nodeTag-1].possibleMinWeight>A[x-1].possibleMinWeight+(l->weight))
A[l->nodeTag-1].possibleMinWeight=A[x-1]+(l->weight);
}
l=l->next;
}
}
return A;
}
To write DecreaseKey, you need the priority-queue implementation to maintain a map from nodeTags to locations in the queue. That means updating this map whenever the binary-heap data structure calls for a swap or perhaps choosing a pointer-based implementation like pairing heaps that never moves nodes in memory.
Unless you have a large, somewhat dense graph, DecreaseKey isn't worth it; just insert a node multiple times and ignore duplicate results from ExtractMin. (To detect duplicates: every time I've implemented Dijkstra, I've needed either the distances or the tree. In my programming languages of choice, it's easy enough to shake loose a bit from either array to remember whether each node has been visited.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With