【发布时间】:2013-08-12 16:05:27
【问题描述】:
我正在尝试使用递归回溯算法解决任何给定的数独难题。我的数独求解器有两个问题。首先,它解决了这个难题,但是它会递归备份并在此过程中解开它(解决了大约 4718 次递归并由于某种原因继续进行另外 10000 次左右的备份)。第二个问题源于我试图解决这个问题。我使用全局矩阵 解决方案 来保存解决方案,一旦我找到它,验证我是否使用 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;
}
再次感谢您的宝贵时间,完整的代码和 readin 文件在 github 上的 wechtera/ssolverOO 它是 ssolver.java 文件,readin 是 ssolverin.txt
【问题讨论】:
-
“正在重置”是什么意思?
-
它解决了它,然后继续将它恢复到原来的空拼图,只剩下原来的点。
标签: java recursion sudoku backtracking