Guest User

Untitled

a guest
May 5th, 2015
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1.   //a Priority queue in reverse order, e.g. the least cost is at the top
  2.   priority_queue<Edge, vector<Edge>, std::greater_equal<Edge> > pq;
  3.  
  4.   //initialize visited - false, distances - infinite, previous vertices - -1
  5.   for (int i = 0; i < G.vertices(); ++i) {
  6.     m_visited[i] = false;
  7.     m_dist[i] = -1;
  8.     m_prev[i] = -1;
  9.   }
  10.   m_dist[m_start] = 0;
  11.  
  12.   pq.push(Edge(m_start,0)); //start with the 'start' vertex
  13.   while (!pq.empty()) {
  14.     //pop the min-cost edge from the PQ
  15.     Edge e = pq.top();
  16.     pq.pop();
  17.     m_visited[e.end()] = true;
  18.     if (e.end() == m_end) break; //reached the destination
  19.  
  20.     //iterate through its neighbors
  21.     Edges neighbors = G.neighbors(e.end());
  22.     for (Edges::const_iterator it = neighbors.begin(); it != neighbors.end(); ++it) {
  23.       int neighbor = (*it).end();  //the current neighbor
  24.       int cost = (*it).cost(); //cost of that neighbor
  25.       int alt = m_dist[e.end()] + cost; //distance from the start
  26.  
  27.       //if the neighbor is not already visited, and the new distance is smaller than the already calculated
  28.       //or it is not calculated yet
  29.       //then set the new distance, and put this neighbor into the PQ
  30.       if (!m_visited[neighbor] && (m_dist[neighbor] == -1 || alt < m_dist[neighbor])) {
  31.         m_dist[neighbor] = alt;
  32.         m_prev[neighbor] = e.end();
  33.         pq.push(Edge(neighbor,alt));
  34.       }
  35.     }
  36.   }
Advertisement
Add Comment
Please, Sign In to add comment