Advertisement
vaibhav1906

Dijkstra

Jan 18th, 2022
1,031
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 1 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void addEdge(vector<pair<int,int>> adj[], int u, int v, int w)
  5. {
  6.     adj[u].push_back({v,w});
  7.     adj[v].push_back({u,w});
  8. }
  9. void dijkstra(vector<pair<int,int>> adj[], int V, int source)
  10. {
  11.     vector<int> dis(V,-1);
  12.     vector<int> vis(V,0);
  13.     priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> p;
  14.     p.push({0,source});
  15.     while(!p.empty())
  16.     {
  17.         pair<int,int> q=p.top();
  18.         p.pop();
  19.         int d=q.first;
  20.         int vertex=q.second;
  21.         if(vis[vertex]==1)
  22.             continue;
  23.         vis[vertex]=1;
  24.         dis[vertex]=d;
  25.         for(auto x:adj[vertex])
  26.         {
  27.             if(vis[x.first]==0)
  28.                 p.push({d+x.second,x.first});
  29.         }
  30.     }
  31.     for(int i=0;i<V;i++)
  32.         cout<<dis[i]<<" ";
  33. }
  34.  
  35. void printGraph(vector<pair<int,int>> adj[], int V)
  36. {
  37.     for (int v = 0; v < V; ++v)
  38.     {
  39.         cout << "Adjacency list of vertex "
  40.              << v << "\n";
  41.         for (auto x : adj[v])
  42.            cout << x.first <<" "<<x.second<<endl;
  43.         cout<<"\n";
  44.     }
  45. }
  46. int main()
  47. {
  48.     int V = 5;
  49.     vector<pair<int,int>> adj[V];  
  50.     addEdge(adj,0, 1, 9);
  51.     addEdge(adj,0, 3, 4);
  52.     addEdge(adj,1, 3, 8);
  53.     addEdge(adj,3, 2, 3);
  54.     addEdge(adj,3, 4, 10);
  55.     vector<int> vis(V,0);
  56.     printGraph(adj,V);
  57.     dijkstra(adj,V,4);
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement