Skip to content

Commit

Permalink
Create DijkstraUsingPQ.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored Jul 1, 2024
1 parent b200b16 commit d4f1a2d
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Graphs/DijkstraUsingPQ.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution
{
public:
//Function to find the shortest distance of all the vertices
//from the source vertex S.
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
{
// Code her
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq;
vector<int>dist(V,1e9);
dist[S]=0;

// {dist,node}
pq.push({0,S});
while(!pq.empty()){
int dis=pq.top().first;
int node=pq.top().second;
pq.pop();
for(auto it:adj[node]){
int edgeW=it[1];
int adjNode=it[0];
if(dis+edgeW<dist[adjNode]){
dist[adjNode]=dis+edgeW;
pq.push({dist[adjNode],adjNode});
}
}
}
return dist;
}
};

0 comments on commit d4f1a2d

Please sign in to comment.