在我的数独代码中,我的布尔值返回真值,但它并没有停止运行,它没有给我正确的答案。
我的代码 dost 如果为真,则不会给出任何值,不会显示错误或其他内容,但如果代码返回 false,则它会给我正确的答案。
我想知道我的代码中发生了什么
public static boolean isSafe(int sudoku[][], int row, int col, int digit) {
// row
for (int i = 0; i < 9; i++) {
if (sudoku[i][col] == digit) {
return false;
}
}
// coloumn
for (int j = 0; j < 9; j++) {
if (sudoku[row][j] == digit) {
return false;
}
}
// grid
int startRow = (row / 3) * 3;
int startCol = (col / 3) * 3;
// 3 X 3 grid
for (int i = startRow; i < startRow + 3; i++) {
for (int j = startCol; j < startCol + 3; j++) {
if (sudoku[i][j] == digit) {
return false;
}
}
}
return true;
}
public static boolean sudokuSolver(int sudoku[][], int row, int col) {
// Base case
if (row == 9) {
return true;
}
// recursion
int nextRow = row;
int nextCol = col+1;
if (col+1 == 9) {
nextRow = row+1;
nextCol = 0;
}
// check place value is zero or somethingelse
if (sudoku[row][col] != 0) {
sudokuSolver(sudoku, nextRow, nextCol);
}
// placement of digit
for (int digit = 1; digit <= 9; digit++) {
if (isSafe(sudoku, row, col, digit)) {
sudoku[row][col] = digit;
if (sudokuSolver(sudoku, nextRow, nextCol)) {
return true;
}
sudoku[row][col] = 0;
}
}
return false;
}
public static void printSudoku(int sudoku[][]) {
System.out.println("----- SUDOKU ----");
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(sudoku[i][j] + " ");
}
System.out.println();
}
}
public static void main(String args[]) {
int sudoku[][] = { { 0, 0, 8, 0, 0, 0, 0, 0, 0 },
{ 4, 9, 0, 1, 5, 7, 0, 0, 2 },
{ 0, 0, 3, 0, 0, 4, 1, 9, 0 },
{ 1, 8, 5, 0, 6, 0, 0, 2, 0 },
{ 0, 0, 0, 0, 2, 0, 0, 6, 0 },
{ 9, 6, 0, 4, 0, 5, 3, 0, 0 },
{ 0, 3, 0, 0, 7, 2, 0, 0, 4 },
{ 0, 4, 9, 0, 3, 0, 0, 5, 7 },
{ 8, 2, 7, 0, 0, 9, 0, 1, 3 }, };
if (sudokuSolver(sudoku, 0, 0)) {
System.out.println("Solution exist");
} else {
System.out.println("Solution not exist");
}
}
} ```