So i am writing a program to solve 8 puzzle using BFS,A*, and UCS. The goal state is fixed according to the assignment which is given as:
Goal State:
|1 2 3|
|8 4|
|7 6 5|
My Initial State:
| 1 2|
|8 4 3|
|7 6 5|
However, upon writing a getInvCount(int [] a)
method:
public static boolean getInvCount(int [] a)
{
int [] arr = a;
int inv_count = 0;
for(int i = 0;i<arr.length-1;i++){
for(int j = i + 1; j < arr.length;j++){
if(arr[i]>arr[j]){
inv_count++;
}
}
}
System.out.println(inv_count);
I realize that the initial puzzle has 9 inversions which is an odd number. Yet the program successfully finds the solution. Is there something I am missing in the requirements for a puzzle to be deemed solvable?
Your
getInvCount
function is only valid for the "1 2 3 4 5 6 7 8" goal state. An "inversion" is when two tiles are in a different order than they are in the goal state. The comparisonarr[i] > arr[j]
is only a correct check for an inversion if the goal state is strictly increasing.