public class FifteenPuzzle {
//---------------------------------------------------
public static boolean solvable15Puzzle(int[][] b) {
int r = b.length;
int c = b[0].length;
int[] a = new int[r * c - 1];
if (!(r == 4) && !(c == 4)) {
System.out.println("อาเรย์ 2 มิติที่ได้รับมาไม่ตรงตามเงื่อนไขกำหนด");
return false;
}
int k = 0;
int B = 0;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (!(b[i][j] == 0)) {
a[k] = b[i][j];
k++;
} else {
B = B+i+1;
}
}
}
int l = a.length;
int L = 0;
for (int i = 0; i <l-1; i++) {
for (int j = i+1; j < l; j++) {
if (a[j]<a[i]) {
L++;
}
}
}
return((L+B)%2==0);
}
//---------------------------------------------------
public static void main(String[] a) {
int[][] ok = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 12, 15 },
{ 13, 14, 11, 0 } };
int[][] nok = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 15, 14, 0 } };
System.out.println(solvable15Puzzle(ok));
System.out.println(solvable15Puzzle(nok));
}
}
|