一次计算即可得到指定点到所有位置的最短路径
#include <iostream>
#include <set>
#include <map>
#include <unordered_map>
#include <queue>
/*
A 5 B 1 C
1 1 1
D 1 E 2 F
*/
typedef int VertexID;
std::unordered_map<VertexID, std::map<VertexID, double>> mapEdges = {
{ 0, { {1, 5}, {3, 1}}},
{ 1, { {0, 5}, {2, 1}, {4, 1}}},
{ 2, { {1, 1}, {5, 1}}},
{ 3, { {0, 1}, {4, 1}}},
{ 4, { {1, 1}, {3, 1}, {5, 2}}},
{ 5, { {2, 1}, {4, 2}}}
};
struct PathNode
{
VertexID pos;
VertexID from;
double distance = std::numeric_limits<double>::max();
bool operator < (const PathNode& other) const noexcept
{
if (distance != other.distance) {
return distance < other.distance;
}
else {
return pos < other.pos;
}
}
};
std::unordered_map<VertexID, PathNode> dijkstra(const std::unordered_map<VertexID, std::map<VertexID, double>>& mapEdges, VertexID source)
{
std::unordered_map<VertexID, PathNode> searchedNode;
searchedNode.reserve(mapEdges.size());
PathNode sourceNode = { source, source, 0 };
searchedNode[source] = sourceNode;
std::priority_queue<PathNode> openNodes;
openNodes.push(sourceNode);
while (openNodes.size() > 0) {
PathNode current = openNodes.top();
openNodes.pop();
for (auto& [neighborPos, edgeLength] : mapEdges.at(current.pos)) {
PathNode& neighborNode = searchedNode[neighborPos];
double newDistance = current.distance + edgeLength;
if (newDistance < neighborNode.distance) {
PathNode newDistanceNode = { neighborPos, current.pos, newDistance };
neighborNode = newDistanceNode;
openNodes.push(newDistanceNode);
}
}
}
return searchedNode;
}
int main(int argc, const char* argv[]) {
VertexID source = 0;
std::unordered_map<VertexID, PathNode> path = dijkstra(mapEdges, source);
VertexID dest = 2; // from A to C
std::cout << path[dest].distance << std::endl; // output 4
std::cout << dest << "\t";
while (dest != source) {
dest = path[dest].from;
std::cout << dest << "\t";
}
}