This section describes a Solution class for problems.
One of the byproducts of a breadth-first or depth-first graph search
is the
predecessor tree.
The predecessor tree contains every vertex that is reachable by the
search from a start vertex
start.
If the problem's goal state is represented in the tree by
vertex
end, then the path from
start to
end can be
generated from the tree using
predecessor links created during
the search.
If the search performed was breadth-first, then the path from
start
to
end will be minimal.
An eventual requirement of the problem solving framework is for the
user to be able to request a solution to the current problem.
Once the problem is solved, the user will want to click through the
moves in the solution from the current state to the goal state.
To accomplish this we need a class, which we call
Solution, that
delivers vertices one at a time from
start to
end as the user
requires them.
Solution is an example of a Java
iterator.
The Java Standard Library defines an
Iterator<E>
interface in the
java.util package.
Classes that implement
Iterator<E> are intended to iterate
over collections of objects of type
E.
Iterator<E> has two abstract methods that must be provided by
implementing classes:
- hasNext: returns true if the iterator has
another object (of type E) to deliver, false otherwise
- next: returns the current object (of type E) in the
collection and advances the iterator to the next object, if any
Once implemented, the
Solution class can be used as shown below
in the
SolutionTest class, which uses the
ExampleGraph
from before (see menu).
Note that besides providing the
hasNext and
next methods,
the
Solution class has a
getLength method that returns
the number of moves (not the number of vertices) in the solution.
The
Solution class
is slightly complicated by the fact that although the order of iteration is
from
start to
end, you must begin your solution
processing with
end.
- The reason is that once a graph has been searched
using breadth-first or depth-first search, its vertices are linked
with predecessor information that can be used to show a problem
solution. Only links going from end to start are
available to construct the solution.
- Thus, a stack is a natural structure for processing
solutions:
- Starting at end, push vertices onto the stack
while following predecessor vertices, stopping when there are no
more predecessors.
- The stack will then have the start
vertex on the top, and the vertices from start
to end can be processed by popping the stack.
A template for
Solution.java is shown in the menu at left.