我发现这个数独求解器在尝试解决难题时使用回溯,为了更好地理解,我想延迟这个过程,以便分析回溯。但我真的不知道该怎么做。我尝试使用Thread.sleep(100);
,但我真的不知道到底该把延迟放在哪里。
abstract class SudoKiller {
private SudokuBoard sb; // Puzzle to solve;
public SudoKiller(SudokuBoard sb) {
this.sb = sb;
}
private boolean check(int num, int row, int col) {
int r = (row / sb.box_size) * sb.box_size;
int c = (col / sb.box_size) * sb.box_size;
for (int i = 0; i < sb.size; i++) {
if (sb.getCell(row, i) == num ||
sb.getCell(i, col) == num ||
sb.getCell(r + (i % sb.box_size), c + (i / sb.box_size)) == num) {
return false;
}
}
return true;
}
public boolean guess(int row, int col) {
int nextCol = (col + 1) % sb.size;
int nextRow = (nextCol == 0) ? row + 1 : row;
try {
if (sb.getCell(row, col) != sb.EMPTY)
return guess(nextRow, nextCol);
}
catch (ArrayIndexOutOfBoundsException e) {
return true;
}
for (int i = 1; i <= sb.size; i++) {
if (check(i, row, col)) {
sb.setCell(i, row, col);
if (guess(nextRow, nextCol)) {
return true;
}
}
}
sb.setCell(sb.EMPTY, row, col);
return false;
}
}
整个项目可以在作者网站上找到。