以下是我称之为回溯的情况。
outerloop: for (int k = 1; k < 11; k++) {
if (k == 10) {
int[][] fixed = backtrack(table, empties);
if(fixed==null){
return null;
}
return Sudokusolution(fixed, 9, 9);
}
其中k是我试图插入空位的数字。
这是我的回溯算法。堆栈孔是最初为空的数组的索引。
public static int[][] backtrack(int[][] goback, Stack<Integer> holes) {
int a;
int b;
int x;
ArrayList<Integer> well = new ArrayList<Integer>();
outerloop2: while (!holes.isEmpty()) {
b = holes.pop();
a = holes.pop();
x = goback[a][b];
System.out.println(x);
if (a < 3 && b < 3) {
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
well.add(goback[a][b]);
}
}
}
if (a < 3 && b > 2 && b < 6) {
for (int row = 0; row < 3; row++) {
for (int col = 3; col < 6; col++) {
well.add(goback[a][b]);
}
}
}
if (a < 3 && b > 5) {
for (int row = 0; row < 3; row++) {
for (int col = 6; col < 9; col++) {
well.add(goback[a][b]);
}
}
}
if (a > 2 && a < 6 && b < 3) {
for (int row = 3; row < 6; row++) {
for (int col = 0; col < 3; col++) {
well.add(goback[a][b]);
}
}
}
if (a > 2 && a < 6 && b > 2 && b < 6) {
for (int row = 3; row < 6; row++) {
for (int col = 3; col < 6; col++) {
well.add(goback[a][b]);
}
}
}
if (a > 2 && a < 6 && b > 5) {
for (int row = 3; row < 6; row++) {
for (int col = 6; col < 9; col++) {
well.add(goback[a][b]);
}
}
}
if (a > 5 && b < 3) {
for (int row = 6; row < 9; row++) {
for (int col = 0; col < 3; col++) {
well.add(goback[a][b]);
}
}
}
if (a > 5 && b > 2 && b < 6) {
for (int row = 6; row < 9; row++) {
for (int col = 3; col < 6; col++) {
well.add(goback[a][b]);
}
}
}
if (a > 5 && b > 5) {
for (int row = 6; row < 9; row++) {
for (int col = 6; col < 9; col++) {
well.add(goback[a][b]);
}
}
}
innerloop: for (int i = x + 1; i < 1; i++) {
if (i == 10) {
continue outerloop2;
}
goback[a][b] = i;
for (int l = b + 1; l < 9; l++) {
if (i == goback[a][l]) {
goback[a][b] = 0;
continue innerloop;
}
}
for (int m = b - 1; m > -1; m--) {
if (i == goback[a][m]) {
goback[a][b] = 0;
continue innerloop;
}
}
for (int n = a + 1; n < 9; n++) {
if (i == goback[n][b]) {
goback[a][b] = 0;
continue innerloop;
}
}
for (int o = a - 1; o > -1; o--) {
if (i == goback[o][b]) {
goback[a][b] = 0;
continue innerloop;
}
}
if (well.contains(i)) {
goback[a][b] = 0;
continue innerloop;
}
return goback;
}
}
return null;
}
感谢任何帮助。谢谢!