-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstra.cpp
57 lines (48 loc) · 1.99 KB
/
Dijkstra.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "pch.h"
#include <queue>
#include "Graph.h"
// =============================================================================
// Dijkstra ====================================================================
// =============================================================================
void Dijkstra(CGraph& graph, CVertex* pStart) {
DijkstraQueue(graph, pStart);
}
// =============================================================================
// DijkstraQueue ===============================================================
// =============================================================================
void DijkstraQueue(CGraph& graph, CVertex *pStart) {
// Assign infinite distance to all vertices, except the start vertex
for (auto& vertex : graph.m_Vertices) {
vertex.m_DijkstraDistance = std::numeric_limits<double>::max();
vertex.m_DijkstraVisit = false;
}
pStart->m_DijkstraDistance = 0.0;
if (graph.m_Edges.empty()) {
return;
}
// Initialize a priority queue
struct comparator {
bool operator()(pair<CVertex*, double> pairLeft, pair<CVertex*, double> pairRight) const {
return pairLeft.second > pairRight.second;
}
};
priority_queue<pair<CVertex*, double>, std::vector<pair<CVertex*, double>>, comparator> queue;
queue.emplace(pStart, 0.0);
while(!queue.empty()) {
const auto currentVertex = queue.top().first;
queue.pop();
if (!currentVertex->m_DijkstraVisit) {
for (auto const edge : currentVertex->m_Edges) {
auto const adjacentVertex = edge->m_pDestination;
// Calculate the dijkstra distance of the adjacent vertices
const auto tentativeDistance = currentVertex->m_DijkstraDistance + edge->m_Length;
if (tentativeDistance < adjacentVertex->m_DijkstraDistance) {
adjacentVertex->m_DijkstraDistance = tentativeDistance;
adjacentVertex->m_pDijkstraPrevious = edge;
queue.emplace(adjacentVertex, tentativeDistance);
}
}
currentVertex->m_DijkstraVisit = true;
}
}
}