Search algorithms for the 8-puzzle solution
include
DepthFirstSolver.hpp
Go to the documentation of this file.
1
/**
2
* @author Douglas De Rizzo Meneghetti (douglasrizzom@gmail.com)
3
* @date 2017-6-23
4
* @brief 8-puzzle exploration based on a depth-first search strategy
5
*/
6
7
#
ifndef
SEARCH_DEPTHFIRSTSOLVER_HPP
8
#
define
SEARCH_DEPTHFIRSTSOLVER_HPP
9
10
#
include
<
LinkedList
.
hpp
>
11
#
include
<
DynamicStack
.
hpp
>
12
#
include
"Solver.hpp"
13
#
include
"GameAction.hpp"
14
15
//! 8-puzzle exploration based on a depth-first search strategy
16
class
DepthFirstSolver
:
public
Solver
{
17
private
:
18
19
int
maxDepth
;
20
21
public
:
22
23
DepthFirstSolver
() :
maxDepth
(- 1) {
24
// no limits in depth
25
}
26
27
//! \param maxDepth the maximum depth allowed for exploration
28
explicit
DepthFirstSolver
(
int
maxDepth) :
maxDepth
(maxDepth > - 1 ? maxDepth : - 1) {
29
}
30
31
LinkedList
<
GameState
*>
solve
(
Game
&
game
,
GameState
&
g0
) {
32
// use a stack to organize states, states that were reached last will be the
33
// first ones to be evaluated
34
DynamicStack
<
GameState
*>
expanded
;
35
36
const
clock_t
start
=
clock
();
37
expanded
.
push
(&
g0
);
38
int
currentMaxDepth
= 0;
39
40
while
(!
expanded
.
isEmpty
()) {
41
GameState
*
currentGame
=
expanded
.
pop
();
42
43
if
(
currentGame
->
getDepth
() >
currentMaxDepth
) {
44
currentMaxDepth
=
currentGame
->
getDepth
();
45
}
46
47
// useful only for debugging
48
// cout << currentGame->getDepth() << '\t' << visited.getSize() << '\t' << expanded.getSize() << endl;
49
50
// check for goal
51
if
(*
game
.
getGoal
() == *
currentGame
) {
52
solved
=
true
;
53
return
endSearch
(
currentGame
,
start
);
54
}
55
56
// expand children, but check the maximum allowed depth before inserting
57
// them in the exploration stack
58
LinkedList
<
GameState
*>
children
=
visit
(
currentGame
);
59
60
if
((
maxDepth
== - 1) || (
currentGame
->
getDepth
() <
maxDepth
)) {
61
while
(!
children
.
isEmpty
()) {
62
expanded
.
push
(
children
.
remove
(0));
63
}
64
}
65
}
66
throw
invalid_argument
(
"This game is unsolvable!"
);
67
}
68
};
69
70
#
endif
// SEARCH_DEPTHFIRSTSOLVER_HPP
DepthFirstSolver::maxDepth
int maxDepth
Definition:
DepthFirstSolver.hpp:19
DepthFirstSolver::DepthFirstSolver
DepthFirstSolver(int maxDepth)
Definition:
DepthFirstSolver.hpp:28
Solver::solve
virtual LinkedList< GameState * > solve(Game &g, GameState &gs)=0
Explores the game tree in search of the goal state.
DepthFirstSolver::solve
LinkedList< GameState * > solve(Game &game, GameState &g0)
Explores the game tree in search of the goal state.
Definition:
DepthFirstSolver.hpp:31
DepthFirstSolver::DepthFirstSolver
DepthFirstSolver()
Definition:
DepthFirstSolver.hpp:23
Generated by
1.8.13