28 #include <unordered_map>
29 #include <unordered_set>
40 inline std::vector<T>
get_path(T start, T end, std::function<std::vector<T>(T)> g, std::function<
float(T, T)> h) {
42 std::unordered_map<T, float> cost_map;
44 std::unordered_map<T, T> prev_map;
46 std::unordered_set<T> visited;
48 auto comp = [](
const auto& a,
const auto& b) {
return a.first > b.first; };
50 std::priority_queue<std::pair<float, T>,
51 std::vector<std::pair<float, T>>,
55 cost_map[start] = 0.f;
56 queue.push({ 0.f, start });
57 while(!queue.empty()) {
58 auto current = queue.top().second;
63 if(visited.count(current))
continue;
64 visited.insert(current);
67 if(current == end)
break;
70 for(
const auto neighbor : g(current)) {
72 if(visited.count(neighbor))
continue;
73 const float cost = cost_map[current] + h(current, neighbor);
75 if(!cost_map.count(neighbor) || cost < cost_map[neighbor]) {
76 cost_map[neighbor] = cost;
77 const float priority = cost + h(neighbor, end);
78 queue.push({ priority, neighbor });
79 prev_map[neighbor] = current;
86 path.reserve(std::abs(
static_cast<long>(start) -
static_cast<long>(end)));
88 while(current != start) {
89 path.push_back(current);
90 current = prev_map[current];
92 path.push_back(start);
96 template<
typename T,
typename V>
97 inline void from_source(T source,
const std::vector<std::vector<V>>& neighbour_rels, std::vector<float>& costs) {
98 auto cmp = [](
const V& a,
const V& b) {
return a.cost < b.cost; };
99 std::priority_queue<V, std::vector<V>, decltype(cmp)> heap;
100 heap.emplace(0.f, source);
101 while(!heap.empty()) {
102 auto vertex = heap.top();
104 if(vertex.cost < costs[vertex.key]) {
105 costs[vertex.key] = vertex.cost;
106 const auto& neighbours = neighbour_rels[vertex.key];
107 for(
const auto& neighbour : neighbours)
108 if(neighbour.cost < costs[neighbour.key])
109 heap.emplace(neighbour.cost, neighbour.key);
std::vector< T > get_path(T start, T end, std::function< std::vector< T >(T)> g, std::function< float(T, T)> h)
Implements the A* algorithm with euclidean distance as heuristic. Returns a vector where the starting...
void from_source(T source, const std::vector< std::vector< V >> &neighbour_rels, std::vector< float > &costs)