除了求解方法之外,算法中的一切似乎都运行良好。当它使用可解数独板执行程序时,它会说无法解决。我已经尝试了解决方法中我能想到的一切。我尝试过调试,但在测试第一行后失败。有什么建议么?这是到目前为止的完整代码:
public class SudokuSolver {
public static void initializeGrid(int[][] grid, int[][] puzzle) {
for (int r = 0; r < puzzle.length; r++) {
for (int c = 0; c < puzzle[0].length; c++) {
grid [r][c] = puzzle [r][c];
}
}
}
public static void displayGrid(int[][] grid) {
for (int r = 0; r < grid.length; r++) {
if (r % 3 == 0) {
System.out.println("+---+---+---+");
}
for (int c = 0; c < grid[r].length; c++) {
if (c % 3 == 0) {
System.out.print("|");
}
displayDigits(r, c, grid);
}
System.out.print("|");
System.out.println();
}
System.out.println("+---+---+---+");
}
if (网格[r][c] == 0) {
System.out.print(' ');
}
别的 {
System.out.print(grid[r][c]);
}
}
公共静态 int getEmptyCells(int[][] grid, int[][] emptyCells) {
整数 i = 0;
int numEmptyCells = 0;
for (int r = 0; r
私有静态布尔 hasNoDuplicates(int[]digitsList) {
for (int j = 0; j
私有静态布尔 checkCurrentRow(int[][] grid, int currentRow) {
int[]digitsList = new int[grid.length];
for (int c = 0; c
私有静态布尔 checkCurrentCol(int[][] grid, int currentCol) {
int[]digitsList = new int[grid.length];
for (int i = 0; i
私有静态布尔 checkCurrentRegion(int[][] grid, int currentRow, int currentCol) {
int[]digitsList = new int[grid.length];
当前行 = (当前行 / 3) * 3;
当前列 = (当前列 / 3) * 3;
整数 i = 0;
for (int r = 0; r
公共静态布尔 isConsistent(int[][] grid, int currentRow, int currentCol) {
if (checkCurrentRow(网格, currentRow) && checkCurrentCol(网格, currentCol)
&& checkCurrentRegion(网格, currentRow, currentCol)) {
返回真;
}
返回假;
}
公共静态布尔solvePuzzle(int [] []网格,int [] []emptyCells,int numEmptyCells){
整数 i = 0;
整数 j = 0;
int currentCellDigit = grid[emptyCells[i][0]][emptyCells[i][1]];
while (j
返回真;
}
公共静态无效主(字符串[] args){
最终 int 大小 = 9;
int[][] 谜题 = { {0,2,9,0,0,3,0,0,5},
{5,0,7,0,0,0,0,9,0},
{6,0,0,0,0,9,4,2,0},
{3,0,2,0,0,4,0,0,0},
{0,0,5,0,3,0,7,0,0},
{0,0,0,5,0,0,6,0,2},
{0,9,8,4,0,0,0,0,3},
{0,3,0,0,0,0,1,0,6},
{2,0,0,3,0,0,9,4,0}
};
int[][] grid = new int[SIZE][SIZE];
int[][]emptyCellsList = new int[SIZE*SIZE][2];
int numEmptyCells = 0;
initializeGrid(grid, puzzle);
numEmptyCells = getEmptyCells(grid, emptyCellsList);
System.out.println("The puzzle:");
displayGrid(puzzle);
if (solvePuzzle(grid, emptyCellsList, numEmptyCells)) {
System.out.println("has been solved:");
displayGrid(grid);
}
else {
System.out.println("cannot be solved!");
}
}
}