

When multiple solutions are counted, the last number removed is put back into the puzzle and then it continues on selecting non-empty squares to try to remove.Īfter completing the rounds, we are left with the puzzle from above.
#Sudoku generator algorithm java code
In the code the rounds variable starts at 3 and is decremented each time we find multiple solutions to a puzzle, so that it won't just stop after the first time it encounters a puzzle with multiple solutions. I've made a copy of the grid for each iteration of removing numbers and testing to see if there is a unique solution. In this code, numbers are removed one at a time and each time the puzzle is tested to see how many solutions there are. A puzzle might not even exist with a certain exact number of clues. You could indicate a certain number of clues you want to leave in the puzzle - but this might take forever to run because it might have to backtrack a lot in order to have exactly the number of clues. There are a few ways you could go about removing the numbers. #if there is more than one solution, put the last removed cell back into the grid #might need to put the square value back if there is more than one solution While rounds > 0 and non_empty_squares_count >= 17: Non_empty_squares_count = len(non_empty_squares) Non_empty_squares = self.get_non_empty_squares(id) """remove numbers from the grid to create the puzzle"""

Remove numbersĪfter generating a complete solution grid, it's time to start removing numbers to create the puzzle. It calls other functions to determine whether or not the current number choice already exists in the same row, column, or box. The function valid_location checks whether or not a number choice can legally be put in a square.
#Sudoku generator algorithm java full
If there is a partial solution grid and the algorithm gets through all of the rest of the squares without reaching a full solution, then the function returns False and backtracks by replacing the last square in the partial solution with a 0 and starting over. The function returns True if there are no more empty squares. The number choices 1-9 are shuffled(a random permutation of their order is generated) because otherwise the same solution grid would be generated each time. So we test each number in each square and recursively check the rest of the board until we find a solution, which is why it's a brute force algorithm.

