Sudoku game in java with source code

broken image

When the algorithm has completed its job, what you get is a solved grid, and after that, all I do is remove some digits randomly from the grid, and I let the player take it from there. Yes I am, because the algorithm won't quit until every space in the grid contains a valid number, and this validity is checked for each digit inserted in the grid. This explains why the grid generation sometimes takes a while to get done. From experience, a solvable Sudoku grid can be generated within 10 attempts (most of the time, under 4 or 5 attempts) with this algorithm. If I detect such an impass, I simply restart the grid generation from scratch. This works well for the first few digits, but the problem is that the more digits you successfully insert into the grid, the closer you get to reaching a logical impass which makes the grid unsolvable. If I detect a collision within the same row or column, I rollback one step and randomly select another spot in the same region. For each digit (1 to 9), I randomly place one instance of that digit in each 3x3 region of the grid. I didn't spend too much time investigating existing algorithms documented on the web, so if my algorithm was already 'invented' by someone else, it's purely coincidental.Īnyhow, my algorithm is of the 'rollback if caught in an impass' variety. What algorithm for grid generation do you use?

broken image