Question: c++ help. How to use Dijkstra to find the minimum path between 2 vertices? Can you write the code? Thanks The implementation for Dijkstras algorithm
c++ help. How to use Dijkstra to find the minimum path between 2 vertices? Can you write the code? Thanks
The implementation for Dijkstras algorithm using the priority queue.class DijkElem {
public:
int vertex, distance;
DijkElem() { vertex = -1; distance = -1; }
DijkElem(int v, int d) { vertex = v; distance = d; }
};
// Dijkstras shortest paths algorithm with priority queue
void Dijkstra(Graph* Graph1, int* distance1, int source1) {
int i, currentVertex, weight; // v is current vertex DijkElem temp;
DijkElem E[Graph1->e()]; // Heap array with lots of space
temp.distance = 0;
temp.vertex = source1;
E[0] = temp; // Initialize heap array heap
H(E, 1, Graph1->e()); // Create heap
for (i=0; in(); i++) { // Now, get distances
do {
if (H.size() == 0) return; // Nothing to remove
temp = H.removefirst();
currentVertex = temp.vertex;
}
while (Graph1->getMark(currentVertex) == VISITED);
Graph1->setMark(currentVertex, VISITED);
if (distance1[v] == INFINITY) return; // Unreachable vertices
for (weight=G->first(v); wn();
w = Graph1->next(v,w))
if (distance1[weight] > (distance1[currentVertex] + Graph1->weight(v, w))) {
// Update D
distance1[weight] = distance[currentVertex] + Graph1->weight(v, w);
temp.distance = distance1[weight];
temp.vertex = weight;
H.insert(temp); // Insert new distance in heap
} } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
