diff --git "a/C++ Codes/Dijkstra\342\200\231s Algorithm" "b/C++ Codes/Dijkstra\342\200\231s Algorithm" new file mode 100644 index 0000000..3750886 --- /dev/null +++ "b/C++ Codes/Dijkstra\342\200\231s Algorithm" @@ -0,0 +1,42 @@ +#include +using namespace std; +int main(){ + int n=5,m=6,source=1; + vector > g[n+1]; // assuming 1 based indexing of graph + // Constructing the graph + g[1].push_back({2,2}); + g[1].push_back({4,1}); + g[2].push_back({1,2}); + g[2].push_back({5,5}); + g[2].push_back({3,4}); + g[3].push_back({2,4}); + g[3].push_back({4,3}); + g[3].push_back({5,1}); + g[4].push_back({1,1}); + g[4].push_back({3,3}); + g[5].push_back({2,5}); + g[5].push_back({3,1}); + // Dijkstra's algorithm begins from here + priority_queue,vector >,greater>> pq; + vector distTo(n+1,INT_MAX);//1-indexed array for calculating shortest paths + distTo[source] = 0; + pq.push(make_pair(0,source)); // (dist,source) + while( !pq.empty() ){ + int dist = pq.top().first; + int prev = pq.top().second; + pq.pop(); + vector >::iterator it; + for( it = g[prev].begin() ; it != g[prev].end() ; it++){ + int next = it->first; + int nextDist = it->second; + if( distTo[next] > distTo[prev] + nextDist){ + distTo[next] = distTo[prev] + nextDist; + pq.push(make_pair(distTo[next], next)); + } + } + } + cout << "The distances from source " << source << " are : \n"; + for(int i = 1 ; i<=n ; i++) cout << distTo[i] << " "; + cout << "\n"; + return 0; +}