Sudoku Algorithms
Sudoku Algorithms
Sudoku algorithms
The class of Sudoku puzzles consists of a partially completed row-column grid of cells partitioned into N regions or
zones each of size N cells, to be filled in using a prescribed set of N distinct symbols (typically the numbers {1, ...,
N}), so that each row, column and region contains exactly one of each element of the set. The puzzle can be solved
using a variety of algorithms. This page provides algorithms only.
Now, applying the exact cover problem, we find members of disjoint from each other and from each member of
, resulting in the collection of 81 disjoint four-element subsets of U whose union is exactly the 324 element
set U.
This representation of the Sudoku problem eliminates all mention of rows, columns, blocks, and values from the
implementation. Instead, we always work with the same collection of 729 four-element subsets of a 324 element
universe. These can be represented by the integers 0 to 728, together with a function f(i,j) which is true if the subsets
corresponding to i and j are disjoint. f might be implemented using a 7292 = 531441 element (66431 byte) constant
bit vector. A specific puzzle is a set of fewer than 81 integers with f(i,j) true for each pair i,j. Solving the puzzle
involves repeatedly finding a new integer k which passes f(i,k) for each i in the partially completed puzzle, and
backtracking when no such k can be found.
Obviously, once we find that a specific k fails f(i,k) for some i, we need not consider it again so long as i remains in
the proposed solution. So we keep a list of k values which have not yet failed. The length of this list estimates the
amount of work required to discover that the current proposed solution fails. So at each level of recursion, we can
look ahead one level to estimate how much work each proposed k will involve, and choose the k which returns
failure in the shortest time.
Although the size of the complete search tree is fixed for a given puzzle, this representation of the problem gives a
fast test for failure at each level, and a way of ordering the search so that the smallest subtrees are searched first.
With this approach and an efficient library for solving exact cover problems, one can solve 9×9 Sudokus in such a
short time on a modern PC that measuring the computation time becomes challenging.
developed variations of the brute force algorithm which will solve this
puzzle in a minute or less with a 3 GHz computer processor.
An extremely simplistic brute force algorithm written in the C language running on a 2.2 GHz processor solved the
above puzzle in just over a minute. Hence, the choice of programming language is obviously important. Further, a
trivial modification to that simplistic algorithm is to rotate the puzzle prior to beginning the iterations allowing for
the easiest angle of attack. By looking at the puzzle from four different angles, the program can quickly deduce
which angle is likely to result in the most iterations. With that one modification, the same 2.2 GHz processor was
able to solve the above puzzle in about a half a second.
One programmer has created charts of the progression of a pointer as it advances through the 81 positions of a
Sudoku using a brute force algorithm. An example is the chart for the solution to a Sudoku "Star Burst Leo" shown
here.[1] [2]
Chart of cell position for solution to "Star Burst Leo" when solved by a brute force
algorithm
17 No No No No Yes No No
(asterisk indicates this number of givens does not have a pattern with this class of symmetry)
Two examples of symmetrical Sudokus with a small number of givens are shown here:
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;
• Undo the color assignments from the neighboring colors hash table.
• Before the search begins, read the initial color assignment.
• Compute the set of vertices to be assigned a color, i.e. not present in the initial assignment.
• Compute the initial state of the hash table of neighbor colors.
• Start the search.
The above algorithm can enter into loops. To detect this, add a hash table that stores seen configurations. When this
happens, terminate the computation and indicate FAIL (e.g. by throwing an exception). Repeat with a different seed
of the random number generator if desired.
(0..8).each { |i|
l = readline
matrix[i] = []
(0..8).each { |j|
matrix[i][j] = l[j..j].to_i
}
}
matrix
end
def permissible(matrix, i, j)
ok = [true,true,true,true,true,true,true,true,true]
# Same as another in the column isn't permissible...
(0..8).each { |i2|
next if matrix[i2][j] == 0
ok[matrix[i2][j] - 1] = false
}
# Same as another in the row isn't permissible...
(0..8).each { |j2|
next if matrix[i][j2] == 0
ok[matrix[i][j2] - 1] = false
}
# Same as another in the 3x3 block isn't permissible...
igroup = (i / 3) * 3
jgroup = (j / 3) * 3
(igroup..(igroup + 2)).each { |i2|
(jgroup..(jgroup + 2)).each { |j2|
next if matrix[i2][j2] == 0
ok[matrix[i2][j2] - 1] = false
}
}
# Convert to the array format...
ret = []
(0..8).each { |i2| ret.push(i2 + 1) if ok[i2] }
Sudoku algorithms 9
ret
end
def deep_copy_sudoku(matrix)
newmat = []
(0..8).each { |i|
newmat[i] = []
(0..8).each { |j|
newmat[i][j] = matrix[i][j]
}
}
newmat
end
def solve_sudoku(matrix)
while true
options = []
(0..8).each { |i|
(0..8).each { |j|
next if matrix[i][j] != 0
p = permissible(matrix, i, j)
# If nothing is permissible, there is no solution at this
level.
return false if (p.length == 0)
options.push({:i => i, :j => j, :permissible => p})
}
}
# If the matrix is complete, we have a solution...
return matrix if options.length == 0
omin = options.min { | a, b |
a[:permissible].length <=> b[:permissible].length
}
return ret
end
}
def print_matrix(matrix)
if (matrix == false)
print "Impossible\n"
return
end
(0..8).each { |i|
(0..8).each { |j|
print matrix[i][j]
}
print "\n"
}
end
print_matrix(solve_sudoku(read_matrix()))
/**
* The standard Sudoku relation is defined by following predicate:
* - R -- row number
* - C -- column number
* - A -- 3x3 area number
*/
related(vt(R,_,_), vt(R,_,_)).
related(vt(_,C,_), vt(_,C,_)).
related(vt(_,_,A), vt(_,_,A)).
/**
* Brute force Sudoku solver (graph colouring).
*
* For all vertices(1) choose a color from Colors, such
* that none of the related vertices have the same color.
* Grouping constraints are encoded in releatd(V1, V2) predicate.
Sudoku algorithms 11
*/
sudoku_solve([], _, _, Solution, Solution).
sudoku_solve([V | Vr], Colors, Hints, Solution, Result) :-
s(V,Ch) in Hints -> % already given as hint
sudoku_solve(Vr, Colors, Hints, [s(V,Ch) | Solution], Result)
; (
C in Colors, %try next color
forall(s(Vs1,Cs1) in Hints, (Cs1 \= C ; not(related(V, Vs1)))),
% hints reserved
forall(s(Vs2,Cs2) in Solution, (Cs2 \= C ; not(related(V,
Vs2)))), % ensure color is unique
sudoku_solve(Vr, Colors, Hints, [s(V,C) | Solution], Result)
%repeat for the rest
).
% define board
test_board(B) :-
colors(C),
def_row_board(C, C, [], B).
def_row_board([], _, S, S).
def_row_board([R | Rs], C, B, S) :-
def_col_board(R, C, B, S1),
def_row_board(Rs, C, S1, S).
s(vt(3,8,3), 6),
s(vt(4,1,4), 8),
s(vt(4,5,5), 6),
s(vt(4,9,6), 3),
s(vt(5,1,4), 4),
s(vt(5,4,5), 8),
s(vt(5,6,5), 3),
s(vt(5,9,6), 1),
s(vt(6,1,4), 7),
s(vt(6,5,5), 2),
s(vt(6,9,6), 6),
s(vt(7,2,7), 6),
s(vt(7,7,9), 2),
s(vt(7,8,9), 8),
s(vt(8,4,8), 4),
s(vt(8,5,8), 1),
s(vt(8,6,8), 9),
s(vt(8,9,9), 5),
s(vt(9,5,8), 8),
s(vt(9,8,9), 7),
s(vt(9,9,9), 9)].
% query solution
test(S) :-
test_board(B),
colors(C),
hints(H),
sudoku_solve(B, C, H, [], S).
Poster: coloin
Label: Platinum Blonde
.......12........3..23..4....18....5.6..7.8.......9.....85.....9...4.5..47...6...
. . . | . . . | . 1 2
. . . | . . . | . . 3
. . 2 | 3 . . | 4 . .
------+-------+------
. . 1 | 8 . . | . . 5
. 6 . | . 7 . | 8 . .
. . . | . . 9 | . . .
------+-------+------
. . 8 | 5 . . | . . .
9 . . | . 4 . | 5 . .
4 7 . | . . 6 | . . .
References
[1] "flickr.com/photos/npcomplete/" (http:/ / www. flickr. com/ photos/ npcomplete/ )
[2] "flickr.com/photos/npcomplete/2384354604/" (http:/ / www. flickr. com/ photos/ npcomplete/ 2384354604/ ) (Star Burst Leo sudoku)
[3] 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] "Sudoku as a constraint problem" (http:/ / 4c. ucc. ie/ ~hsimonis/ sudoku. pdf)
[6] "JaCoP" (http:/ / jacop. osolpro. com)
[7] "17 Clue Sudoku with Diagonal Symmetry" (http:/ / www. flickr. com/ photos/ npcomplete/ 2599486458/ )
[8] "19 Clue Two-Way Symmetry" (http:/ / www. flickr. com/ photos/ npcomplete/ 2896377811/ )
[9] "The hardest sudokus" (http:/ / forum. enjoysudoku. com/ the-hardest-sudokus-new-thread-t6539. html) On the New Sudoku Players' Forums
[10] "what is the hardest known suduko ?" (http:/ / www. setbb. com/ sudoku/ viewtopic. php?t=103& start=0& mforum=sudoku) On the Sudoku
Programmers Forums
[11] "How regular is to generate sudoku with difficulty 9+ SE?" (http:/ / forum. enjoysudoku. com/
how-regular-is-to-generate-sudoku-with-difficulty-9-se-t5336. html) On the New Sudoku Players' Forums
Sudoku algorithms 15
External links
• http://diuf.unifr.ch/people/juillera/Sudoku/Sudoku.html Sudoku Explainer by Nicolas Juillerat (Popular for
rating Sudokus in general)
• http://www.research.att.com/~gsf/man/man1/sudoku.html sudoku by gsf (Popular for rating the hardest
Sudokus amongst other things)
• http://magictour.free.fr/sudoku.htm''suexrat9 by dukuso (Popular for rating the hardest sudokus)
• http://magictour.free.fr/suexratt.exe suexratt by dukuso (Popular for rating the hardest sudokus)
• http://www.emanueleferonato.com/2008/12/09/sudoku-creatorsolver-with-php/ Sudoku creator/solver using
Php
• http://www.idontplaydarts.com/code/sudoku-solver/ An open source PHP Sudoku solver class using a Depth
first Search
• A Pencil-and-Paper Algorithm for Solving Sudoku Puzzles (http://www.ams.org/notices/200904/
rtx090400460p.pdf) quoted also in a popular British newspaper the Daily Mail (http://www.dailymail.co.uk/
news/article-1163925/Puzzling-behaviour-Maths-professor-finds-formula-solve-ANY-Sudoku.html)
• Downloadable Excel Sudoku Assistant and Solver (http://home.comcast.net/~raagnew/site/?/page/
Downloads)
• Solving sudoku in PL/pgSQL (http://www.microshell.com/database/postgresql/
solving-sudoku-using-postgresql-plpgsql/) from Microshell.
• Solving Sudoku in APL (http://aplwiki.com/SudokuSolver/).
• Interactive Excel Sudoku solver, using only Excel formulas (http://www.excelhero.com/blog/2010/07/
excel-formula-based-sudoku-solver.html).
• Interactive Javascript Sudoku solver, Only Javascript (http://personal.telefonica.terra.es/web/jagar/Sudoku/
Sudoku.htm).
Article Sources and Contributors 16
License
Creative Commons Attribution-Share Alike 3.0 Unported
http:/ / creativecommons. org/ licenses/ by-sa/ 3. 0/