我在解决逻辑求解算法方面遇到了问题。它可以很好地解决具有大量提示的难题,但是对于少于45个线索的难题存在问题。
这是用于解决的算法。Immutable是一个布尔值,用于确定该值是否可以更改。cell [row] [col]。possibleValues是SudokuCell类中LinkedList的一部分,其中存储该格元素可能的值。 grid.sGrid是谜题的主int [] []数组。 removeFromCells()是从网格的行、列和象限中删除值的方法。该代码在下面提供。
第二个for循环仅用于检查单个解决方案。我决定避免使用递归,因为我真的无法理解它。这种方法现在似乎足够好用。
这是用于解决的算法。Immutable是一个布尔值,用于确定该值是否可以更改。cell [row] [col]。possibleValues是SudokuCell类中LinkedList的一部分,其中存储该格元素可能的值。 grid.sGrid是谜题的主int [] []数组。 removeFromCells()是从网格的行、列和象限中删除值的方法。该代码在下面提供。
第二个for循环仅用于检查单个解决方案。我决定避免使用递归,因为我真的无法理解它。这种方法现在似乎足够好用。
public boolean solve(){
for(int i = 0; i < 81; i++){
for(int row = 0; row < 9; row++){
for(int col = 0; col < 9; col++){
if(!immutable[row][col]){
if(cell[row][col].getSize() == 1){
int value = cell[row][col].possibleValues.get(0);
grid.sGrid[row][col] = value;
immutable[row][col] = true;
removeFromCells(row, col, value);
}
}
}
}
}
int i = 0;
for(int row = 0; row < 9; row++){
for(int col = 0; col < 9; col++){
if(grid.sGrid[row][col] == 0){
i++;
}
}
}
if(i != 0){
return false;
} else{
return true;
}
}
这是removeFromCells()的代码。
我认为大部分代码都很容易理解。第一个for循环从(x, y)所在的行和列中删除值,第二个循环从象限中删除值。
public void removeFromCells(int x, int y, int value){
/*
* First thing to do, find the quadrant where cell[x][y] belong.
*/
int topLeftCornerRow = 3 * (x / 3) ;
int topLeftCornerCol = 3 * (y / 3) ;
/*
* Remove the values from each row and column including the one
* where the original value to be removed is.
*/
for(int i = 0; i < 9; i++){
cell[i][y].removeValue(value);
cell[x][i].removeValue(value);
}
for(int row = 0; row < 3; row++){
for(int col = 0; col < 3; col++){
cell[topLeftCornerRow + row][topLeftCornerCol + col].removeValue(value);
}
}
}
可能有问题的地方是可能值的构建。这是我用于此的方法:
第一个for循环创建新的SudokuCells以避免可怕的空指针异常。
sGrid中的任何null值都表示为0,因此for循环跳过它们。
SudokuBoard的构造函数调用此方法,所以我知道它正在被调用。
public void constructBoard(){
for(int row = 0; row < 9; row++){
for(int col = 0; col < 9; col++){
cell[row][col] = new SudokuCell();
}
}
immutable = new boolean[9][9];
for(int row = 0; row < 9; row++){
for(int col = 0; col < 9; col++){
immutable[row][col] = false;
if(grid.sGrid[row][col] != 0){
removeFromCells(row, col, grid.sGrid[row][col]);
immutable[row][col] = true;
}
}
}
}
我会将整个文件发布出来,但里面有很多不必要的方法。我已经张贴了我认为导致问题的部分。
if(i != 0){ return false; } else{ return true; }
等价于return (i != 0);
吗?(第一个代码块) - user unknown