Like this:

Related

9 Responses to “Sudoku”

Some time back I had read Peter Norvig’s beautiful post Solving Every Sudoku Puzzle, and tried to convert his program into Haskell. His idea, in short, was to use constraint propagation to fill up as many values as possible; and then ultimately search.

Though the resulting Haskell program was not as succinct as his original Python, I thought it wasn’t too bad either. Perhaps using some monad trick (that I yet have to learn!) all the checks against ‘Nothing’ can be eliminated.

Solving sudoku is interseting.
How about designing sudoku puzzles that have exactly one solution?
Does anyone have an idea how to do that?
I can think of the following:
0: Initially all fields are unoccupied.
1: Randomly choose an unoccupied field.
2: Take all consistent digits in arbitrary order.
3: If there are no consistent digits backtrack from step 1.
4: Try the digits in arbitrary order.
5: For each trial solve the puzzle to a maximum of two solutions.
6: If there is no solution, try the next consistent digit or backtrack from step 1 if no digits are left.
7: If there is one solution we are ready.
9: If there is more than one solution, try to complete the puzzle from step 1.

This is a solution in php that uses backtracking.
You start with a first empty cell and the least number that fits there (i.e. with no conflict from other numbers that are already supplied in the puzzle).
And apply the same logic to the next empty cell, till you’re not able to fill any number in an empty cell – at which time you backtrack to the previous cell, change the number there and try again.

So for the above Sudoku puzzle, since the first empty cell is in (1,2), the function below will first be invoked as:
solve(1,1,2)
$game_table is just an array of 9X9 that already contains supplied numbers in the puzzle
$complete will be set to FALSE before calling solve() for the first time

while($number<=9 && !$complete)
{
//check is this number can fit into this cell
if(check_horizontal($number,$row,$column) && check_vertical($number,$row,$column) && check_square($number,$row,$column))
{
$game_table[$row][$column]=$number; //no conflict, so fill the cell with this number
//find the next blank cell
$i=1;$j=1;$found=false;