-
Notifications
You must be signed in to change notification settings - Fork 0
/
astar.hpp
56 lines (54 loc) · 1.36 KB
/
astar.hpp
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
#pragma once
#include <vector>
#include <limits>
#include <queue>
namespace astar{
template<typename cost_type>
struct node;
template<typename cost_type>
using edge = std::pair<node<cost_type>*, cost_type>;
template<typename cost_type>
struct node{
std::vector<edge<cost_type>> edges;
cost_type tentative, heuristic;
node(
decltype(edges) edges = {},
decltype(tentative) tentative
= std::numeric_limits<decltype(tentative)>::max(),
decltype(heuristic) heuristic = 0
): edges(edges), tentative(tentative), heuristic(heuristic){}
};
template<typename cost_type>
cost_type path(node<cost_type>& start, decltype(start) goal){
auto priority = [](
const node<cost_type>* lhs,
const node<cost_type>* rhs
){
return lhs->tentative
+ lhs->heuristic
> rhs->tentative
+ rhs->heuristic;
};
std::priority_queue<
node<cost_type>*,
std::vector<node<cost_type>*>,
decltype(priority)
> open_set(priority);
start.tentative = 0;
open_set.push(&start);
while(!open_set.empty()){
auto n = open_set.top();
if(n == &goal) return goal.tentative;
open_set.pop();
for(auto& i: n->edges){
if(i.first->tentative
== std::numeric_limits<cost_type>::max()
){
i.first->tentative = n->tentative + i.second;
open_set.push(i.first);
}
}
}
return std::numeric_limits<cost_type>::max();
}
};