Implementing Dijkstra Algorithm | Practice | GeeksforGeeks

Given a weighted, undirected and connected graph of V vertices and E edges, Find the shortest distance of all the vertex's from the source vertex S.
Note: The Graph doesn't contain any negative weight cycle.
 
Example 1:
Input:

S = 0
Output:
0 9
Explanation:
The source vertex is 0. Hence, the shortest 
distance of node 0 is 0 and the shortest 
distance from node 9 is 9 - 0 = 9.

 
Example 2:
Input:

S = 2
Output:
4 3 0
Explanation:
For nodes 2 to 0, we can follow the path-
2-1-0. This has a distance of 1+3 = 4,
whereas the path 2-0 has a distance of 6. So,
the Shortest path from 2 to 0 is 4.
The other distances are pretty straight-forward.

 
Your Task:
You don't need to read input or print anything. Your task is to complete the function dijkstra()  which takes number of vertices V and an adjacency list adj as input parameters and returns a list of integers, where ith integer denotes the shortest distance of the ith node from Source node.  Here adj[i] contains a list of lists containing two integers where the first integer j denotes that there is an edge between i and j and second integer w denotes that the weight between edge i and j is w.
 
Expected Time Complexity: O(V2).
Expected Auxiliary Space: O(V2).
 
0
smdakhtar0071 day ago
// done using  Stack data structure done in 0.09 
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)
    {
        set<pair<int,int>>st;
        vector<int> distance(V,INT_MAX);
        distance[S] = 0 ;
        st.insert({0,S});
        while(!st.empty()){
            pair<int,int>temp = *st.begin();
            st.erase(st.begin());
            int node = temp.second;
            int nxt_dis = temp.first; 
            for(auto it : adj[node]){
                if(distance[it[0]] > nxt_dis + it[1]){
                    distance[it[0]] = nxt_dis+it[1];
                    st.insert({distance[it[0]],it[0]});
                }
            }
            
        }
        return distance;
        
        
    }
};
+1
aarushsrivastava5 days ago
 vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
    {
        // Code here
        priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> q;
        vector<int> dist(V, INT_MAX);
        dist[S] = 0;
        q.push({0, S});
        while(!q.empty()){
            int node = q.top().second;
            int dis = q.top().first;
            q.pop();
            for(auto it : adj[node]){
                int next = it[0];
                int nextdis = it[1];
                if(dis + nextdis < dist[next]){
                    dist[next] = dis + nextdis;
                    q.push({dist[next], next});
                }
            }
        }
      return dist;
    }
0
amishasahu3281 week ago
vector<int> dijkstra(int V, vector<vector<int>> adj[], int S)
    {
        // Code here
        // By default, C++ creates a max-heap for priority queue.
        // // min-heap ; In pair => (dist,from)
        priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
        vector<int> distance(V+1, INT_MAX);
        distance[S] = 0;
        pq.push({0,S});
        while(!pq.empty())
        {
            int dis = pq.top().first;
            int prev = pq.top().second;
            pq.pop();
            for(auto it: adj[prev])
            {
                if(distance[it[0]] > distance[prev]+it[1]){
                    distance[it[0]] = distance[prev]+it[1];
                    pq.push({distance[it[0]], it[0]});
                }
            }
        }
        return distance;
    }
0
itsmemritu1 week ago
 typedef pair<int, int> pii;   vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)   {       // Code here              vector<int>ans(V,INT_MAX);       priority_queue<pii,vector<pii>,greater<pii>>pq;       vector<bool>visited(V,false);       ans[S]=0;       pq.push({0,S});       while(!pq.empty()){          int k=pq.top().second;          int t=pq.top().first;          pq.pop();          if(visited[k]){              continue;          }          visited[k]=true;          for(auto it:adj[k]){              int weight=it[1];              int v=it[0];              if(ans[v]>ans[k]+weight){                  ans[v]=ans[k]+weight;                  pq.push({ans[v],v});              }          }       }       return ans;   }
+1
pawananjanimth12 weeks ago
Solution using Set:
 vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
    {
        // Code here
        vector<int> dist(V+1,INT_MAX);
        
        dist[S]=0;
        
        set<pair<int,int>> st;
        
        st.insert({S,0});
        
        while(!st.empty())
        {
            pair<int,int> p = *(st.begin());
            
            int node = p.first;
            
            int node_dist = p.second;
            
            st.erase(p);
            
            for(auto v:adj[node])
            {
                if(node_dist+v[1]<dist[v[0]])
                {
                    if(st.find({v[0],v[1]})!=st.end()) st.erase({v[0],v[1]});
                    
                    dist[v[0]] = node_dist + v[1];
                    
                    st.insert({v[0],dist[v[0]]});
                }
            }
            
        }
        
        
        return dist;
    }
0
sknwd88643 weeks ago
  vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)   {       // Code here              // dijkstra's algorithm using priority_queue              vector<int> dist(V , INT_MAX); // distance array              dist[S]=0;      // in min heap , we  Store weight & node weight first then node               vector<bool> visited(V , false);              priority_queue< pair<int , int> , vector<pair<int , int>> , greater< pair<int , int>>> pq;              pq.push({0 , S});              while(!pq.empty())       {           auto t= pq.top();           pq.pop();                     // int w=t.first;           int node=t.second;                      visited[node]=true;           // traverse its adjacent                       for(int i=0;i<adj[node].size();i++)           {               int v=adj[node][i][0];               int w=adj[node][i][1];                              if(visited[v]==false)               {                   if(dist[v]>dist[node] + w  )                   {                       dist[v]=dist[node] + w;                                              // value i.e distance is updated                                               // it is not INT_MAX                        pq.push({dist[v] , v});                   }               }           }                             }              return dist;                 }
+1
devashishbakare3 weeks ago
Java Solution with explanation
 
class Solution
{
    static class pair implements Comparable<pair>{
   int ver;
   int wt;
   public pair(int n,int d)
   {
       this.wt=d;
       this.ver=n;
   }
   public int compareTo(pair p)
   {
       return this.wt - p.wt;
   }
}

   //Function to find the shortest distance of all the vertices
   //from the source vertex S.
   static int[] dijkstra(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj, int S)
   {
       // Write your code here
       //create ans array and initised them as a infinity
       int[] ans=new int[V];
       Arrays.fill(ans,Integer.MAX_VALUE);
       
       //source shortest length always zero
       ans[S]=0;
       
       PriorityQueue<pair> pq = new PriorityQueue<>();
       
       //add first element with 0 as distance
       pq.add(new pair(S,0));
       
       while(pq.size()>0)
       {
         
           pair p = pq.poll();
         
         //get the adjucent of all the pop vertex  
           for(ArrayList<Integer> x:adj.get(p.ver))
           {
               //if newly found path is smaller thean the previous path,
               
               if( ans[p.ver] + x.get(1) < ans[x.get(0)] )
               {
                   //then update the sortest path 
                   ans[x.get(0)] = ans[p.ver]+x.get(1);
                   
                   //add that element in priority queue for next element to move shotest weightt
                   //coz its greedy approtch
        
                   pq.add(new pair(x.get(0),ans[x.get(0)]));
                   
               }
           }
       }
       //returning the final answer
       return ans;
   }
}
0
shivam26120023 weeks ago
 vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)   {            vector<int> dist(V,INT_MAX);      dist[S]=0;      queue<int> q;      q.push(S);            while(!q.empty()){                    int node=q.front();          q.pop();         for(auto i:adj[node])          {            if(dist[node]+i[1]<dist[i[0]]) {               dist[i[0]]=dist[node]+i[1];                            q.push(i[0]);}          } }        return dist;   }
0
19bcs13143 weeks ago
 
my solution using priority queue using bfs 

class Pair implements Comparable<Pair> {
        int v,wt;

        Pair(int v,int wt){
            this.v=v;
            this.wt=wt;
        }
        
        public int compareTo(Pair obj){
            return this.wt-obj.wt;
        }
}

class Solution
{
    //Function to find the shortest distance of all the vertices
    //from the source vertex S.
    static int[] dijkstra(int v, ArrayList<ArrayList<ArrayList<Integer>>> adj, int src)
    {

        int ans[]=new int[v];

        PriorityQueue<Pair> q=new PriorityQueue<>();
        
        q.add(new Pair(src,0));
        boolean[] visit=new boolean[v];
        while(q.size()!=0){
            Pair temp=q.remove();
            
            if(visit[temp.v]==true){
                continue;
            }
            visit[temp.v]=true;
            ans[temp.v]=temp.wt;

            ArrayList<ArrayList<Integer>> l=adj.get(temp.v);
            
            for(int i=0;i<l.size();i++){
                ArrayList<Integer> ls=l.get(i);
                
                int u=ls.get(0);
                    int wet=ls.get(1);
                
                if(visit[u]==false ){
                        q.add(new Pair(u,temp.wt+wet));
                }
            }
            
        }

        return ans;
        
        
    }
}

0
saurabhsathe12344 weeks ago
C++ : 0.1 ms
1 . Without using min heap :
 
 vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
    {
        // Code here
        vector<int> dist(V,INT_MAX);
        vector<int> fin(V,false);
        dist[S] = 0;
        for(int c=0;c<V;c++)
        {
            int u = -1;
            for(int i=0;i<V;i++)
            {
                if( !fin[i] && (u==-1 || dist[i] < dist[u]))
                {
                    u=i;
                }
            }
            
            fin[u] = true ;
            
            for(auto it : adj[u]){
                int node = it[0];
                int d = it[1];
                if( !fin[node] && (dist[node] > dist[u] + d))
                {
                    dist[node] = dist[u] + d;
                }
            }
            
        }
        return dist;
        
    }
2. with min heap :
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
    {
        // Code here
        vector<int> dist(V,INT_MAX);
        vector<int> fin(V,false);
        priority_queue< pair<int,int> , vector<pair<int,int>> , 
                        greater<pair<int,int>> > pq;
                        
        
        dist[S] = 0;
        pq.push({0,S});
        
        while(!pq.empty())
        {
            int u = pq.top().second;
            fin[u] = true;
            
            for(auto it : adj[u]){
                int node = it[0];
                int d = it[1];
                if( !fin[node] && (dist[node] > dist[u] + d))
                {
                    dist[node] = dist[u] + d;
                    pq.push({dist[node],node});
                }
            }
            pq.pop();
        }
        
        return dist;
        
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.