-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAStar.h
119 lines (101 loc) · 2.77 KB
/
AStar.h
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
//
// Created by matan on 1/15/20.
//
//
// Created by matan on 1/15/20.
//
#ifndef HW4_SEARCHALGORITHMS_ASTAR_H_
#define HW4_SEARCHALGORITHMS_ASTAR_H_
#include <queue>
#include <unordered_map>
#include "State.h"
#include "interfaces.h"
template<typename T> Solution<T> createSolutionFromGoalA(State<T>* goalState, State<T>& start)
{
Solution<T> sol;
State<T>* curr = goalState;
cout<<"price: "<<curr->getCost()<<"\n";
if(goalState)
{
sol.addMove(curr);
curr = curr->getPrev();
while(!curr->equals(start))
{
sol.addMove(curr);
curr = curr->getPrev();
}
sol.addMove(curr);
return sol;
}
throw "NO GOAL STATE";
}
template <typename T> struct LessThanByPriceAndH
{
bool operator()(State<T>*& first, State<T>*& second) const
{
double firstH = first->heuristicDistance();
double secondH = second->heuristicDistance();
return first->getCost() + firstH > second->getCost() + secondH;
}
};
template<typename T> class AStar : public ISearcher<T>{
std::priority_queue<State<T>*, vector<State<T>*>, LessThanByPriceAndH<T>> queue;
unordered_map<string, State<T>*> closedList;
int numOfNodeExpended = 0;
//queue.push(State);
public:
ISearcher<T>* clone()
{
return new AStar();
}
int numberOfNodeExpended()
{
return numOfNodeExpended;
}
Solution<T> search(ISearchable<T>* problem) {
auto first = problem->getInitialState();
queue.push(first);
closedList.insert(make_pair(first->getStateString(), first));
while(queue.size() != 0)
{
State<T>* minState = queue.top();
queue.pop();
numOfNodeExpended++;
if(problem->isGoal(minState))
{
cout<<"num of nodes: "<<numberOfNodeExpended()<<"\n";
return createSolutionFromGoalA<T>(minState, *problem->getInitialState());
}
vector<State<T>*> neighbors = problem->getAllPossibleStates(minState);
for(State<T>* curr : neighbors)
{
if(minState->getCost() + problem->getCost(minState, curr) < curr->getCost())
{
curr->setCost(minState->getCost() + problem->getCost(minState, curr));
if(closedList.find(curr->getStateString()) == closedList.end())
{
curr->setPrev(minState);
closedList.insert(make_pair(curr->getStateString(), curr));
queue.push(curr);
}
else
{
curr->setPrev(minState);
vector<State<T>*> copy;
while(queue.size() != 0)
{
copy.push_back(queue.top());
queue.pop();
}
while(copy.size() != 0)
{
queue.push(copy.back());
copy.pop_back();
}
}
}
}
}
}
};
#endif //HW4_SEARCHALGORITHMS_PRIORITYBASEDALGS_H_