-
Notifications
You must be signed in to change notification settings - Fork 1
/
Astar.cpp
61 lines (54 loc) · 1.78 KB
/
Astar.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
58
59
60
61
#include "Astar.hpp"
vector<MAPPGridState> Astar::astar( MAPPGridState &grid )
{
vector<MAPPGridState> newStates = grid.successors();
if( newStates.size() == 0 )
{/* There is no valid successor */
return {grid};
}
/* A* algo */
priority_queue<MAPPGridState, vector<MAPPGridState>> Q;
Q.push( grid );
MAPPGridState n = grid;
unordered_map<MAPPGridState, MAPPGridState> predecessors;
unordered_map<MAPPGridState, unsigned int> minCost;
minCost.insert({n,0});
bool going = true;
while( !Q.empty() && going )
{
n = Q.top();
Q.pop();
for( auto &succ : n.successors() )
{
/* Min cost */
unsigned int mcn, mcs;
mcn = mapRetrieve( minCost, n );
mcs = mapRetrieve( minCost, succ );
if( mcn + 1 < mcs )
{
minCost.insert( {succ, mcn + 1} );
succ.setCost( mcn + 1 );
Q.push(succ);
predecessors.insert( {succ, n} );
}
}
if( n.getH() == 0 )
{
going = false;
OUTPUT<<"Found a result"<<endline;
}
}
/* vector that holds state trajectory */
vector<MAPPGridState> results;
results.reserve(10);
results.emplace_back(n);
while( !(predecessors.find(n)->second == grid) )
{
n = predecessors.find(n)->second;
results.emplace_back(n);
}
n = predecessors.find(n)->second;
results.emplace_back(n);
std::reverse(results.begin(), results.end());
return results;
}