Solving according to strategies is pretty straightforward. Generating puzzles is more complex and exercises your comfort with recursion. In general terms generating a puzzle follows these steps

  • Create an empty grid
  • Use brute force to solve
  • Remove random ‘sures’ to reach a target number of givens, ensuring that the result is solvable using the level of difficulty strategies you are aiming for.
We are going to deal with the brute force solving part here. The general flow is

.. and here is the code

This is interesting in that it is not only recursive in of itself, but it also calls .Solve which resurses through with Solveiterate.
Brute is implemented as method of the cPuzzle class. It will create a cloned instance of cSudGrid for each recursion, and destroy it if that path is not successful.
It also chooses which cells and which possibilities to try next, randomly, except that for efficiency reasons, the cells are kept sorted into least possibilities first order.
This will keep going,  trying alternate paths and backtracking until it finds a solution to what starts as a blank Sudoku. Since there should always be a solution, it will only reach wrapup if something has gone wrong.

Next steps

As before the entire code will be is downloadable here. Now we have created a completed grid, the next step will be to remove items to the required level of difficulty, and we will have completed the generation of a puzzle.
For help and more information join our community,  follow the blog or  follow me on Twitter.