...
/Solution: Shortest Distance of Each Node from the Source
Solution: Shortest Distance of Each Node from the Source
This review provides a detailed analysis of the solutions to find the shortest distance of each node from the source.
Solution #1: Dijkstra’s Algorithm Using Priority Queue
Dijkstra’s algorithm is an algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks.
The algorithm exists in many variants. Dijkstra’s original variant found the shortest path between two nodes, but a more common variant fixes a single node as the “source” node and finds the shortest paths from the source to all other nodes in the graph, producing a shortest-path tree.
Dijkstra’s algorithm finds the shortest path between a
and b
.
It picks the unvisited vertex with the lowest distance,
calculates the distance through it to each unvisited neighbor,
and updates the neighbor’s distance if smaller. Mark visited
(set to red) when done with neighbors.
We use STL Priority Queue for our solution. If you want to get an idea of how they are used, have a look at the appendix.
#include "Graph.h"typedef pair<int, int> myPair;void Graph::shortestPath(int source) {// Syntax for built in Priority queue// use the key word "greater" to use it like a min heap// we want smallest edges to be at the toppriority_queue <myPair, vector <myPair> , greater <myPair>> myPriorityQueue;//array to maintain the shortest edgesvector<int> distanceArray(vertices, INF);//push the source first because source has 0 distance with itselfmyPriorityQueue.push(make_pair(0, source));distanceArray[source] = 0;// now start iterating the queue.while (!myPriorityQueue.empty()) {int u = myPriorityQueue.top().second;myPriorityQueue.pop();list <pair<int, int>>::iterator i;for (i = adjacencyList[u].begin(); i != adjacencyList[u].end(); ++i) {int v = (*i).first;int weight = (*i).second;//update distance of u->v if shorter edge foundif (distanceArray[v] > distanceArray[u] + weight) {distanceArray[v] = distanceArray[u] + weight;// priority queue acts like a min heap so each time only smallest edges at topmyPriorityQueue.push(make_pair(distanceArray[v], v));}}}for (int i = 0; i < vertices; ++i)if (i == vertices - 1)cout << i << " --> " << distanceArray[i];elsecout << i << " --> " << distanceArray[i] << ", ";}int main() {int V = 9;int E = 14;Graph g(V, E);g.addEdge(0, 1, 4);g.addEdge(0, 7, 8);g.addEdge(1, 2, 8);g.addEdge(1, 7, 11);g.addEdge(2, 3, 7);g.addEdge(2, 8, 2);g.addEdge(2, 5, 4);g.addEdge(3, 4, 9);g.addEdge(3, 5, 14);g.addEdge(4, 5, 10);g.addEdge(5, 6, 2);g.addEdge(6, 7, 1);g.addEdge(6, 8, 6);g.addEdge(7, 8, 7);cout << "Shortest Distance between source node and all the other nodes"<<endl;cout<<"Graph1: "<<endl;g.shortestPath(0);cout << endl << endl;V = 4;E = 4;Graph g1(V, E);g1.addEdge(0, 1, 1);g1.addEdge(0, 2, 2);g1.addEdge(1, 3, 10);g1.addEdge(2, 3, 5);cout<<"Graph2: "<<endl;g1.shortestPath(0);return 0;}
The algorithm ...