Search algorithms for the 8-puzzle solution
GreedySolver.hpp
Go to the documentation of this file.
1 /**
2  * @author Douglas De Rizzo Meneghetti (douglasrizzom@gmail.com)
3  * @date 2017-6-24
4  * @brief Implementation of a greedy exploration algorithm for the 8-puzzle game.
5  */
6 
7 #ifndef SEARCH_GREEDYSOLVER_HPP
8 #define SEARCH_GREEDYSOLVER_HPP
9 
10 #include <OrderedList.hpp>
11 #include "Solver.hpp"
12 #include "Heuristic.hpp"
13 
14 //! Implementation of a greedy exploration algorithm for the 8-puzzle game.
15 class GreedySolver : public Solver {
16  private:
17 
19 
20  public:
21 
22  //! Initializes the solver
23  //! \param h the heuristic to be used by the algorithm
24  explicit GreedySolver(Heuristic *h) : heuristic(h) {
25  }
26 
28  delete heuristic;
29  }
30 
31  //! Compares two states using the available heuristic.
32  //! The greedy search takes into consideration only the sum of Manhattan distances between pieces in the
33  //! current state to their goal state. The state that has the lowest heuristic is
34  //! considered a more promising exploration candidate.
35  //! \param a
36  //! \param b
37  //! \return 1 if h(a) < h(b), -1 if h(a) > h(b), 0 if h(a) = h(b)
38  static int compare(GameState *a, GameState *b) {
39  Manhattan h;
40 
41  if (h.calc(*a) < h.calc(*b)) return 1;
42 
43  if (h.calc(*a) > h.calc(*b)) return - 1;
44 
45  return 0;
46  }
47 
49  // like A*, keep the states in an OrderedList, sorted by their heuristic value
51 
52  const clock_t start = clock();
53  expanded.insert(&g0);
54  while (! expanded.isEmpty()) {
55  // need only remove the first element, since they are ordered
57 
58  // check for goal
59  if (*game.getGoal() == *currentGame) {
60  solved=true;
61  return endSearch(currentGame, start);
62  }
63 
64  // expand children
66  while (! children.isEmpty()) {
68  }
69  }
70 
71  throw invalid_argument("This game is unsolvable!");
72  }
73 };
74 
75 #endif // ifndef SEARCH_GREEDYSOLVER_HPP
Implementation of the Manhattan distance for the 8-puzzle.
Definition: Heuristic.hpp:23
static int compare(GameState *a, GameState *b)
Compares two states using the available heuristic.
LinkedList< GameState * > solve(Game &game, GameState &g0)
Explores the game tree in search of the goal state.
virtual LinkedList< GameState * > solve(Game &g, GameState &gs)=0
Explores the game tree in search of the goal state.
GreedySolver(Heuristic *h)
Initializes the solver.
int calc(GameState &currentState)
Calculates the heuristic value for a state.
Definition: Heuristic.hpp:26
Describes a single state in the 8-puzzle.
Definition: GameState.hpp:18
Heuristic * heuristic
Abtract class for heuristic functions.
Definition: Heuristic.hpp:13