Jump to content

Sudoku solving algorithms

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Linuxtinkerer (talk | contribs) at 15:31, 26 October 2014 (Updated the citation to Julie Zelenski's lecture to include more information). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Sudoku puzzles are designed to be solved by human players with pencil and paper but with well defined algorithms, it is possible to be solved in almost real time by computer or even smartphone. A standard Sudoku puzzle contains 81 grids which consists 9 grid rows and 9 grid columns. Sudoku have 9 non-overlapping zones which each zones consists of 3 grid rows and 3 grid columns. In each zones, there can be only a number occurring only once in each grid. Players may use a wide range of strategies which deals the solutions either from zones or the whole grid.

Techniques

Backtracking

Backtracking algorithms are adapted to solve the Sudoku that iterates all the possible solutions for the given sudoku. If the solutions assigned does not lead to the solutions of Sudoku, the algorithm discard the solutions and rollback to the original solutions and retried again and hence the name backtracking. [1]

Below is the general pseudocode of backtracking algorithm for standard sudoku template (9x9) [2]

     Initialize 2D array with 81 empty grids(nx=9,ny=9)
     Fill in some empty grid with the known values
     Make an original copy of the array
     Start from top left grid(nx=0,ny=0), check if grid is empty
     if (grid is empty){
     assign the empty grid with values (i) 
       if (no numbers exists in same rows & same columns same as (i) & 3x3 zone (i) is currently in)
       fill in the number
       if (numbers exists in same rows & same columns same as (i) & 3x3 zone (i) is currently in)
       discard (i) and repick other values (i++)
     }else{
       while (nx<9){
         Proceed to next row grid(nx++,ny)
           if (nx equal 9){
           reset nx = 1
           proceed to next column grid(nx,ny++)
               if (ny equal 9){
               print solutions
               }
           }           
     }

Exact cover

Sudoku may be described as an instance of the exact cover problem. This allows both for an elegant description of the problem and an efficient solution using a backtracking algorithm. While exact cover does not guarantee efficient solution times for large grids, implementations of Sudoku using algorithms for exact cover, such as Dancing Links, typically solve 9x9 Sudoku grids with minimal calculation time of the order of seconds.

Brute-force algorithm

Some hobbyists have developed computer programs that will solve Sudoku puzzles using a brute force algorithm. Although it has been established that approximately 6.67 x 1021 final grids exist, using a brute force computer algorithm can be a practical method to solve puzzles if the code is well designed.

Advantages of this method are:

  • a solution is guaranteed (as long as the puzzle is valid)
  • solving time is mostly unrelated to degree of difficulty

The disadvantage of this method is that it may be comparatively slow when compared to computer solution methods modeled after deductive methods.

A brute force algorithm visits the empty cells in some order, filling in digits sequentially from the available choices, or backtracking (removing failed choices) when a dead-end is reached. For example, a brute force program would solve a puzzle by placing the digit "1" in the first cell and checking if it is allowed to be there. If there are no violations (checking row, column, and box constraints) then the algorithm advances to the next cell, and places a "1" in that cell. When checking for violations, it is discovered that the "1" is not allowed, so the value is advanced to a "2". If a cell is discovered where none of the 9 digits is allowed, then the algorithm leaves that cell blank and moves back to the previous cell. The value in that cell is then increased to "2". The algorithm is repeated until a valid solution for all 81 cells is found.

Stochastic search / optimization methods

Sudoku can be solved using stochastic (random-based—search) methods.[3][4] An example of this is:

  1. randomly assigning numbers to the blank cells in the grid
  2. calculate the number of errors
  3. "shuffle" these inserted numbers around the grid until the number of mistakes is reduced to zero

A solution to the puzzle will then have been found. Approaches for shuffling the numbers include simulated annealing, genetic algorithm and tabu search.

Stochastic-based optimisation algorithms are known to be quite fast, though they are perhaps not as fast as some logic-based techniques. Unlike the latter however, optimisation algorithms do not necessarily require problems to be logic-solvable, giving them the potential to solve a wider range of problem instance.

It is also possible to express a Sudoku as an integer linear programming problem. Such approaches seem to get close to a solution quite quickly, and can then use branching towards the end. The Simplex algorithm seems able to handle situations with no solutions or multiple solutions quite well.

Constraint Programming

Sudoku is a constraint problem. "Sudoku as a constraint problem" describes many reasoning algorithms available in the form of constraints which can be applied to model and solve the problem. Some constraint solvers include an example how to model and solve Sudoku problems.[5] [6] The constraint program modeling and solving Sudoku will in most solvers have less than 100 lines of code. If the code employs a strong reasoning algorithm, incorporating a search routine is only needed for the hardest puzzles.

Computation time

Computer algorithms work through increasingly more cycles when searching for Sudokus with 20 clues or fewer. Indeed puzzles with 17 clues are notoriously difficult to find. When the constraint of symmetry is applied, the expected search time will dramatically increase yet further.[7]

Blank Sudoku grids

Although Sudoku grids that come with some of their cells pre-filled can often be quite challenging to solve, blank Sudoku grids can actually be solved very quickly. Perhaps the easiest way of doing this is to produce the root solution, which can be achieved using the following simple polynomial time algorithm.[3]

For the standard n2 x n2 (9 x 9) grid this algorithm (equivalent implementations in java and haskell) is as follows:

final int n = 3;
final int[][] field = new int[n*n][n*n];
for (int i = 0; i < n*n; i++)
	for (int j = 0; j < n*n; j++)
		field[i][j] = (i*n + i/n + j) % (n*n) + 1;
sol :: [[Int]]
sol = [ [ witness (build i j) | j <- [0..heightGame] ]
                              | i <- [0..heightGame] ]
  where
    build i j     = (i * heightRegion) + (i `div` heightRegion) + j
    witness       = (`mod` heightGame) . (+ 1)
    heightRegion  = 3
    heightGame    = heightRegion^2

The above procedure produces the following 9x9 Sudoku:

+-----------------------+
| 1 2 3 | 4 5 6 | 7 8 9 |
| 4 5 6 | 7 8 9 | 1 2 3 |
| 7 8 9 | 1 2 3 | 4 5 6 |
|-------+-------+-------|
| 2 3 4 | 5 6 7 | 8 9 1 |
| 5 6 7 | 8 9 1 | 2 3 4 |
| 8 9 1 | 2 3 4 | 5 6 7 |
|-------+-------+-------|
| 3 4 5 | 6 7 8 | 9 1 2 |
| 6 7 8 | 9 1 2 | 3 4 5 |
| 9 1 2 | 3 4 5 | 6 7 8 |
+-----------------------+

References

  1. ^ Zelenski, Julie (July 16, 2008). Lecture 11 | Programming Abstractions (Stanford). Stanford Computer Science Department.
  2. ^ http://moritz.faui2k3.org/en/yasss
  3. ^ a b Lewis, R (2007) Metaheuristics Can Solve Sudoku Puzzles Journal of Heuristics, vol. 13 (4), pp 387-401.
  4. ^ Perez, Meir and Marwala, Tshilidzi (2008) Stochastic Optimization Approaches for Solving Sudoku arXiv:0805.0697.
  5. ^ "JaCoP"
  6. ^ "Sudokusolver"
  7. ^ "17 Clue Sudoku with Diagonal Symmetry"