我正在尝试使用递归回溯算法解决任何给定的数独谜题。我的数独求解器有两个问题。首先,它可以解决谜题,但在过程中递归返回并取消解决(大约在4718次递归后解决,并继续进行另外10000次左右的递归)。第二个问题源于我尝试解决这个问题。我使用全局矩阵 solution 来保存找到的解决方案,并使用类似于以下内容的isSolved方法验证我已经找到了解决方案:
public static boolean isSolved(int[][]puzzle){
for(int i = 0; i<9; i++){ //y rotation
for(int j = 0; j<8; j++){
if(puzzle[i][j]==0){
return false;
}
}
}
return true;
}
在我的难题中,带有数字0的方块等同于其为空。然而,这似乎也被重置了,但我无法找到它被重置的地方。您有任何指导或建议,或者可以指出我应该查找的地方吗?
以下是我的解决方法,我已经标注了重要的代码行。
public static int[][] solve(int[][]puzzle, int x, int y){
System.out.println("RecrDepth: " + recDepth);
recDepth++;
//using backtracking for brute force power of the gods(norse cause they obviously most b.a.
ArrayList<Integer> list = new ArrayList<Integer>();
//next for both x and y
int nextx = getNextx(x);
int nexty = getNexty(x, y);
while(puzzle[y][x] != 0){ //progress until blank space
x = nextx;
y = nexty;
if(isSolved(puzzle)){
System.out.println("resetting solution improperly");
solution = puzzle;
return puzzle;
}
nextx = getNextx(x);
nexty = getNexty(x, y);
}
for(int i = 1; i<10; i++){
if(isTrue(puzzle, y, x, i)) //isTrue checks column, row and box so we dont go down unnecessary paths
list.add(i);
}
for(int i=0; i<list.size(); i++){ //iterating through options in open squre recursing for each one
puzzle[y][x]= list.get(i);
if(isSolved(puzzle)){
System.out.println("Resetting Solution"); //appears to reset solution here but only once that I see in print out
solution = puzzle;
return puzzle;
}
System.out.print("=");
puzzle = solve(puzzle, nextx, nexty);
puzzle[y][x] = 0;//clear spot upon backtracking THIS WAS WHAT I WAS MISSIN
}
return puzzle;
}
再次感谢您的时间,完整的代码和读取文件已经放在Github上的wechtera/ssolverOO上,其中ssolver.java是代码文件,ssolverin.txt是读取文件。