这是使用 Java BitSet 类的数独板的另一种可能的数据结构。板上的每个单元格都有其可能性,由名为 possibilities 的 BitSet 变量跟踪。
还显示了一个示例eliminateInRow 方法,它从一行中消除数字作为可能性。该方法包括要在行中跳过的列列表,以免除最初导致我们进行消除的单元格(例如,OP 在原始问题的 cmets 中提到的单元格 7 和 9)。还有另一种情况,如果您发现 3 个单元格都包含可能性 (3,5,9)(例如),那么您可以从该行中的所有其他单元格中消除 3,5,9 作为可能性(排除原始的 3 个单元格)。此方法将同时处理 2-case 和 3-case,因为它使用整数 List 表示要跳过的列。
import java.util.BitSet;
import java.util.List;
class SudokuCell {
BitSet possibilities;
CellValue value;
SudokuCell() {
// Initially the value of this cell is undefined
value = CellValue.Undefined;
possibilities = new BitSet(9);
// Initially every value is possible
possibilities.set(0, 9);
}
// clears the possibility of 'number' from this cell
void clear(int number) {
possibilities.clear(number - 1);
// If there is only one possibility left
if (possibilities.cardinality() == 1) {
// Set value of the cell to that possibility
int intValue = possibilities.nextSetBit(0);
value = CellValue.fromInteger(intValue);
}
}
// returns the value of this square if it is defined
int getValue() throws Exception {
if (value == CellValue.Undefined) {
throw new Exception("Undefined cell value");
}
return CellValue.toInteger(value);
}
// returns whether 'num' is still possible in this cell
boolean isPossible(int num) {
return possibilities.get(num-1);
}
}
public class SudokuBoard {
SudokuCell[][] sudokuBoard;
// constructor
SudokuBoard() {
sudokuBoard = new SudokuCell[9][9];
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
sudokuBoard[row][col] = new SudokuCell();
}
}
}
// eliminate the possibility of 'num' from row 'row'
// skipping columns in List skipCols
void eliminateInRow(int row, int num, List<Integer> skipCols) {
for (int col = 0; col < 9; col++) {
if (!skipCols.contains(col)) {
sudokuBoard[row][col].clear(num);
}
}
}
}
下面是enumCellValue的代码,是可选的:
enum CellValue {
Undefined, One, Two, Three, Four, Five, Six, Seven, Eight, Nine;
public static CellValue fromInteger(int x) {
switch (x) {
case 0:
return Undefined;
case 1:
return One;
case 2:
return Two;
case 3:
return Three;
case 4:
return Four;
case 5:
return Five;
case 6:
return Six;
case 7:
return Seven;
case 8:
return Eight;
case 9:
return Nine;
}
return null;
}
public static int toInteger(CellValue value) throws Exception {
switch (value) {
case Undefined:
throw new Exception("Undefined cell value");
case One:
return 1;
case Two:
return 2;
case Three:
return 3;
case Four:
return 4;
case Five:
return 5;
case Six:
return 6;
case Seven:
return 7;
case Eight:
return 8;
case Nine:
return 9;
}
throw new Exception("Undefined Cell Value");
}
}