Skip to content

Instantly share code, notes, and snippets.

@luistelmocosta
Created April 11, 2016 13:53
Show Gist options
  • Save luistelmocosta/7df4a22652beef64c3bdf72c5a16f375 to your computer and use it in GitHub Desktop.
Save luistelmocosta/7df4a22652beef64c3bdf72c5a16f375 to your computer and use it in GitHub Desktop.
template<class T>
void Graph<T>::dijkstraShortestPath(const T &s) {
for(unsigned int i = 0; i < vertexSet.size(); i++) {
vertexSet[i]->path = NULL;
vertexSet[i]->dist = INT_INFINITY;
vertexSet[i]->processing = false;
}
Vertex<T>* v = getVertex(s);
v->dist = 0;
vector< Vertex<T>* > pq;
pq.push_back(v);
make_heap(pq.begin(), pq.end());
while( !pq.empty() ) {
v = pq.front();
pop_heap(pq.begin(), pq.end());
pq.pop_back();
for(unsigned int i = 0; i < v->adj.size(); i++) {
Vertex<T>* w = v->adj[i].dest;
int aValue = v->dist + v->adj[i].distance;
int bValue = w->dist;
bool condition = aValue < bValue;
if(condition) {
w->dist = v->dist + v->adj[i].distance;
w->path = v;
//se já estiver na lista, apenas a actualiza
if(!w->processing)
{
w->processing = true;
pq.push_back(w);
}
make_heap (pq.begin(),pq.end(),vertex_greater_than<T>());
}
}
}
vector<T> returnVector;
for(int i = 0; i < pq.size(); i++){
returnVector.push_back(pq[i]->getInfo());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment