Advertisement
Guest User

dijkstra

a guest
May 19th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. //====================================
  2. //              DIJKSTRA
  3. //====================================
  4.  
  5. VertexT minimum(set<VertexT> T, vector<CostT> D){
  6.     std::set<VertexT>::iterator it = T.begin();
  7.     double min_val = D[(*it)];
  8.     VertexT min_vert = (*it);
  9.  
  10.     for (auto v : T){
  11.         if (D[v] < min_val){
  12.             min_val = D[v];
  13.             min_vert = v;
  14.         }
  15.     }
  16.  
  17.     return min_vert;
  18. }
  19.  
  20.  
  21. void Dijkstra(const DistanceGraph& g, GraphVisualizer& v, VertexT start,
  22.     std::vector<CostT>& D) {
  23.  
  24.     size_t vertexCount = g.numVertices();
  25.     D.resize(vertexCount);   //cost vector
  26.     D[start] = 0;   //optimal distance (start -> start) = 0
  27.  
  28.     //R is set of vertices
  29.     set<VertexT> R;
  30.     for (size_t i = 0; i < vertexCount; i++){
  31.         if (i != start){
  32.             R.insert(i);
  33.         }
  34.     }
  35.  
  36.     //initialise D by iterating over all vertices except start
  37.     for (auto v : R){
  38.         D[v] = g.cost(start,v);
  39.     }
  40.  
  41.     //main loop
  42.     VertexT v1;
  43.     while (!(R.empty())){
  44.         v1 = minimum(R,D);  //finds vertex with minimal distance from v
  45.         R.erase(v1);
  46.  
  47.         for (auto v : R){
  48.             if (D[v] > D[v1] + g.cost(v1,v))
  49.                 D[v] = D[v1] + g.cost(v1,v);
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement