Commit 1b0cf6ce authored by Valentin Platzgummer's avatar Valentin Platzgummer

123

parent 1ccf1519
......@@ -11,7 +11,8 @@ namespace OptimisationTools {
|| startIndex < 0
|| endIndex < 0
|| startIndex >= numElements
|| endIndex >= numElements) {
|| endIndex >= numElements
|| endIndex == startIndex) {
return false;
}
// Node struct
......@@ -107,6 +108,4 @@ namespace OptimisationTools {
return true;
}
// don't seperate parameters with new lines or documentation will break
} // end OptimisationTools namespace
#include "OptimisationTools.h"
#include <QPointF>
namespace OptimisationTools {
namespace {
}
bool dijkstraAlgorithm(const int numNodes,const int startIndex,const int endIndex, QVector<int> &elementPath, std::function<double(const int, const int)> distance)
{
if ( numNodes < 0
|| startIndex < 0
|| endIndex < 0
|| endIndex >= numNodes
|| startIndex >= numNodes
|| endIndex == startIndex) {
return false;
}
// distanceToStart[i] contains the distance of element[i] to element[startIndex] (after successful algorithm termination)
QVector<double> distanceToStart(numNodes, std::numeric_limits<qreal>::infinity());
// elementPredecessor[i] contains the predecessor of element[i]
QVector<int> elementPredecessor(numNodes, -1);
// Elements will be successively removed from this list during the execution of the Dijkstra Algorithm.
QVector<int> workingSet;
workingSet.reserve(numNodes);
//fill workingSet with 0, 1, ..., numNodes-1
for (int i = 0; i < numNodes; i++) workingSet.append(i);
distanceToStart[startIndex] = 0;
// Dijkstra Algorithm
// https://de.wikipedia.org/wiki/Dijkstra-Algorithmus
while (workingSet.size() > 0) {
// serach Node with minimal distance
double minDist = std::numeric_limits<qreal>::infinity();
int minIndex = -1; // index of element with least distance to element[startIndex]
for (int i = 0; i < workingSet.size(); i++) {
int e = workingSet[i];
double dist = distanceToStart[e];
if (dist < minDist) {
minDist = dist;
minIndex = i;
}
}
if (minIndex == -1)
return false;
int u = workingSet.takeAt(minIndex);
if (u == endIndex) // shortest path found
break;
//update distance
double distanceU = distanceToStart[u];
for (int i = 0; i < workingSet.size(); i++) {
int v = workingSet[i];
double dist = distance(u, v);
// is ther a alternative path which is shorter?
double alternative = distanceU + dist;
if (alternative < distanceToStart[v]) {
distanceToStart[v] = alternative;
elementPredecessor[v] = u;
}
}
}
// end Djikstra Algorithm
// reverse assemble elementPath
int e = endIndex;
while (1) {
if (e == -1) {
if (elementPath[0] == startIndex)// check if starting point was reached
break;
return false;
}
elementPath.prepend(e);
//Update Node
e = elementPredecessor[e];
}
return true;
}
// end anonymous namespace
} // end OptimisationTools namespace
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment