Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //a Priority queue in reverse order, e.g. the least cost is at the top
- priority_queue<Edge, vector<Edge>, std::greater_equal<Edge> > pq;
- //initialize visited - false, distances - infinite, previous vertices - -1
- for (int i = 0; i < G.vertices(); ++i) {
- m_visited[i] = false;
- m_dist[i] = -1;
- m_prev[i] = -1;
- }
- m_dist[m_start] = 0;
- pq.push(Edge(m_start,0)); //start with the 'start' vertex
- while (!pq.empty()) {
- //pop the min-cost edge from the PQ
- Edge e = pq.top();
- pq.pop();
- m_visited[e.end()] = true;
- if (e.end() == m_end) break; //reached the destination
- //iterate through its neighbors
- Edges neighbors = G.neighbors(e.end());
- for (Edges::const_iterator it = neighbors.begin(); it != neighbors.end(); ++it) {
- int neighbor = (*it).end(); //the current neighbor
- int cost = (*it).cost(); //cost of that neighbor
- int alt = m_dist[e.end()] + cost; //distance from the start
- //if the neighbor is not already visited, and the new distance is smaller than the already calculated
- //or it is not calculated yet
- //then set the new distance, and put this neighbor into the PQ
- if (!m_visited[neighbor] && (m_dist[neighbor] == -1 || alt < m_dist[neighbor])) {
- m_dist[neighbor] = alt;
- m_prev[neighbor] = e.end();
- pq.push(Edge(neighbor,alt));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment