In order to take elements off the queue in a particular order (lowest
heuristic first), there is a useful
PriorityQueue class
in
java.util.
A
PriorityQueue constructor can be given a
Comparator
object.
- Comparator is a functional interface
- Comparator's lone compare method returns a negative
number if its first argument is less than the second argument
- For our purposes, compare should return a
negative number if the first argument, a state vertex, has a
heuristic that is less than that of its second argument, also a
state vertex
- Therefore, if h1 and h2 are the heuristic values of
the first and second arguments to compare, respectively,
then compare should return h1 - h2
- Since Comparator is a functional interface, it can be
specified through a lambda expression
Best-first search can be implemented by a
BestFirstSolver class
that extends
StateSpaceSolver and specifies the search queue as a
priority queue that compares vertices as described above. A UML diagram
can be seen from the menu.
A listing of
BestFirstSolver.java is also given in the menu,
along with performance results for best-first search. Note that the
solutions found are far from optimal.
Heuristics are a property of states, so they should be computed by
classes that extend the
State abstract class.
Recall the
getHeuristic method in the
State
class, as shown below. Note that for simple problems like the
FWGC problem that do not require heuristics, the heuristic defaults
to zero.