I am making a sudoku solver for a school assignment in Java, using backtracking. I have successfully solved it using a boolean solveSudoku() method but in the template provided by the teacher, the method is listed as void solveSudoku(). It clearly says in the requirements to use the methods as given, but I am having a hard time changing my code.
This is my initial method :
(The int[] findEmptySquare(), as the name suggests returns the indexes of the next empty cell in the sudoku.)
boolean solveSudoku() {
int[] arr = new int[2];
arr = findEmptySquare();
if (arr != null) {
for (int i = 1; i <= 9; i++) {
if (givesConflict(row, col, i) == false) {
int x = row, y = col;
grid[row][col] = i;
if (solveSudoku()) {
return true;
} else {
grid[row][col] = 0;
row = x;
col = y;
}
}
}
return false;
}
//solutionCounter++;
return true;
}
I have tried to mimic the boolean modus operandi in a void method like this :
boolean okay;
void solveSudoku() {
int[] arr = new int[2];
arr = findEmptySquare();
if (arr != null) {
for (int i = 1; i <= 9; i++) {
if (givesConflict(row, col, i) == false) {
int x = row, y = col;
grid[row][col] = i;
if (okay == true) { //line 11
solveSudoku();
okay = true;
return;
} else {
grid[row][col] = 0;
row = x;
col = y;
}
}
}
okay = false;
return;
}
okay = true;
return;
}
Unfortunately, this does not work as intended. If on line 11 I replace it with if(okay == false), the program runs until it gets stuck with no correct number to fill, and then the backtracking doesn't start.
Could anyone provide a hint in what way I can successfully tranform this method? I would greatly appreciate it, thank you!