I am looking to implement a very simple algorithm that uses brute force backtracking to solve Sudoku networks. The problem I'm facing is that in my implementation, I included two instance variables for the Sudoku class called row and col , which correspond to the row and column of the empty cell in the two-dimensional array that represents Sudoku.
When my solve() method executes it, it first checks to see if there are no empty cells, in which case the puzzle is already completed. Otherwise, the same method assigns the row and column of the empty cell to the variables of the row and col instance of the Sudoku object that contains the grid. After that, the for loop checks which number can be placed in this empty cell by calling the isSafe(int n) method (this method checks if the puzzle restrictions are met, I can guarantee that it works fine). Thus, the isSafe() method puts the number in an empty cell and then recursively calls the solve() method again on the Sudoku object.
If we click on a constraint that cannot be met, then we reassign a 0 last row and col that was filled. That's where the problem is found! Since the program constantly updates the row and col variables, then the old instances are lost with every recursive call. I am trying to figure out how to save these values ββso that the program can undo actions when it is reversed. I was thinking about pushing each col and row onto the stack, but I'm really not sure where to go.
Can someone tell me what would be an easy way to approach this problem? I do not include the whole class, if you think that it would be useful, let me know and I will publish it.
class Sudoku { int SIZE, N, row, col; int Grid[][]; public boolean solve() { if (!this.findNextZero()) return true; for (int num = 1; num <= 9; num++) { if (isSafe(num)) { this.Grid[this.row][this.col] = num; if (this.solve()) return true; this.Grid[this.row][this.col] = 0;
If I were to implement a stack, does the following make sense? After the findNextZero() operations, push the integers row and col findNextZero() stack. Keep doing this, and then change the following line of code
this.Grid[this.row][this.col] = 0;
to something like
this.Grid[s.pop][s.pop] = 0;
Is this a smart approach?
java recursion sudoku
Macalaca
source share