|
Here we present a very compact Sudoku Solver. The actual functions for solving the game is less than 40 lines long. The code is written in C++, compiled and tested with Microsoft VC++ 6.0 compiler. A VC++ 6.0 project is included that can be readily built and run. Permission is granted for personal, non-commercial use only. The solver is coded in a C++ class as listed below : class CSudokuSolver
To use the solver, create an instance of the class. Set the fixed values of the puzzle to be solved. Then call function Solve() and check the return value. See the main() function in the project code. Mainly 2 functions are involved in the solving process. The first one is IsValueOkAt(...). This function checks, using Sudoku rules, if a given value is ok or not at a given cell position. The 2nd function is FixCellAt(...). This function is listed below. int
CSudokuSolver::FixCellAt(int ix,int iy)
Notice that this function is recursive(that means it calls itself). It is the recursion that makes the code so compact. In fact, this solution may not be possible without recursion. The solution starts with a call to FixCellAt(0,0). The steps are :
Advantages : The code is very
compact. Multiple solutions, if any, can be found. The solutions (or no
solution) are complete and absolute.
On the other hand, an intuitive solution uses Sudoku logic to solve a puzzle, immitating how a brain works. This method is computationally faster. But the coding is much lengthier and there is no guarantee of a solution, as in case of a human being. A combination of both may be used, as in our Sudoku PC program. Contributor & Copy Right:
Andrew Qu
e-mail:
|