Skip to content

Instantly share code, notes, and snippets.

@caseyscarborough
Last active December 2, 2019 18:45
Show Gist options
  • Save caseyscarborough/6544636 to your computer and use it in GitHub Desktop.
Save caseyscarborough/6544636 to your computer and use it in GitHub Desktop.
This class shows how to determine if a 3x3 sliding puzzle is solvable or not.
/**
* This class represents how to determine the solvability
* of a 3 x 3 sliding puzzle.
*
* @author Casey Scarborough
*/
public class Solvable {
public static void main(String[] args) {
// These puzzles are known solvable.
int[] a = { 0, 1, 2, 4, 5, 3, 7, 8, 6 };
int[] b = { 1, 2, 3, 0, 4, 6, 7, 5, 8 };
int[] c = { 1, 0, 3, 7, 2, 5, 8, 4, 6 };
// These are known not solvable.
int[] d = { 1, 2, 3, 6, 8, 4, 5, 7, 0 };
int[] e = { 1, 2, 3, 4, 5, 6, 8, 7, 0 };
int[] f = { 1, 5, 0, 3, 2, 8, 4, 6, 7 };
if (isSolvable(a) && isSolvable(b) && isSolvable(c))
System.out.println("These puzzles are solvable.");
if (!isSolvable(d) && !isSolvable(e) && !isSolvable(f))
System.out.println("These puzzles are not solvable.");
}
// This method takes a two dimensional array representing
// a sliding puzzle, and determines if it is solvable.
public static boolean isSolvable(int[] p) {
int inversions = 0;
for(int i = 0; i < p.length - 1; i++) {
// Check if a larger number exists after the current
// place in the array, if so increment inversions.
for(int j = i + 1; j < p.length; j++)
if(p[i] > p[j]) inversions++;
// Determine if the distance of the blank space from the bottom
// right is even or odd, and increment inversions if it is odd.
if(p[i] == 0 && i % 2 == 1) inversions++;
}
// If inversions is even, the puzzle is solvable.
return (inversions % 2 == 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment