Question
/** * Finds and return a solution to the problem, consisting of a list of * states. * * The list should start with the
/**
* Finds and return a solution to the problem, consisting of a list of
* states.
*
* The list should start with the initial state of the underlying problem.
* Then, it should have one or more additional states. Each state should be
* a successor of its predecessor. The last state should be a goal state of
* the underlying problem.
*
* If there is no solution, then this method should return an empty list.
*
* @return a solution to the problem (or an empty list)
*/
public List
Queue
frontier.add((T) searchProblem);
Map
successor.put((T) searchProblem, null);
List
while (!frontier.isEmpty()) {
T current = frontier.remove();
for (T next : BaseGraph.getNeighbors(current)) {
if (!successor.containsKey(next)) {
frontier.add(next);
successor.put(next, current);
}
}
if (current.equals(searchProblem)) {
path.add(current);
T previous = successor.get(current);
while (previous != null) {
path.add(0, previous);
previous = successor.get(previous);
}
break;
}
}
return path;
}
/**
* Checks that a solution is valid.
*
* A valid solution consists of a list of states. The list should start with
* the initial state of the underlying problem. Then, it should have one or
* more additional states. Each state should be a successor of its
* predecessor. The last state should be a goal state of the underlying
* problem.
*
* @param solution
* @return true iff this solution is a valid solution
* @throws NullPointerException
* if solution is null
*/
public final boolean isValidSolution(List
int inversions = 0;
for (T i : solution) {
if (solution.get(i) == 0) {
continue;
}
}
for (int i = 0; i < solution.size(); i++) {
if (solution.get(i) == 0) {
continue;
}
for (int j = i; j < solution.size(); j++) {
if (solution.get(j) == 0) {
continue;
}
if (solution.get(j) < solution.get(i)) {
inversions++;
}
}
}
return (inversions & 1) == 0;
}
The bolded part is my work, but I want to know the correct way to do it. Please help, this is for a 8-puzzle game and the method checks if the solution is valid or not, and the other finds the solution.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started