I'm trying to test whether a 15 puzzle is solvable. I wrote a method which is working for most puzzles, but for some not.
For example this puzzle can be solved with two moves (0, 11), (0, 12)
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 11, 13, 14, 15, 12
Here is the puzzle better visualized:
1 2 3 4
5 6 7 8
9 10 0 11
13 14 15 12
But the puzzle has a odd parity of 3 and so should not be solvable.
public boolean isSolvable(int[] puzzle)
{
int parity = 0;
for (int i = 0; i < puzzle.length; i++)
{
for (int j = i + 1; j < puzzle.length; j++)
{
if (puzzle[i] > puzzle[j] && puzzle[i] != 0 && puzzle[j] != 0)
{
parity++;
}
}
}
if (parity % 2 == 0)
{
return true;
}
return false;
}
What am i doing wrong?