views:

668

answers:

4

I want to write a code in python to solve a sudoku puzzle. Do you guys have any idea about a good algorithm for this purpose. I read somewhere in net about a algorithm which solves it by filling the whole box with all possible numbers, then inserts known values into the corresponding boxes.From the row and coloumn of known values the known value is removed.If you guys know any better algorithm than this please help me to write one. Also I am confused that how i should read the known values from the user. It is really hard to enter the values one by one through console. Any easy way for this other than using gui?

+13  A: 

Peter Norvig has written a nice essay on the question:

http://norvig.com/sudoku.html

static_rtti
+2  A: 

I wrote a simple program that solved the easy ones. It took its input from a file which was just a matrix with spaces and numbers. The datastructure to solve it was just a 9 by 9 matrix of a bit mask. The bit mask would specify which numbers were still possible on a certain position. Filling in the numbers from the file would reduce the numbers in all rows/columns next to each known location. When that is done you keep iterating over the matrix and reducing possible numbers. If each location has only one option left you're done. But there are some sudokus that need more work. For these ones you can just use brute force: try all remaining possible combinations until you find one that works.

Hope this helps.

Regards,

Sebastiaan

Sebastiaan Megens
i didnt get what you meant by bit mask.
ragsagar
You use a 16-bit integer where the lower 9 bits specify which of the values are still possible. So '1 is still possible' is specified by the rightmost bit, '2 is still possible' is specified by the second rightmost bit, etc. You can OR these values together and thereby specify a complete state of a location in the sudoku matrix. For example 000001111 means that only 1, 2, 3 and 4 are still possible, the rest is ruled out already by the values of other locations in the matrix. Does that make it more clear?
Sebastiaan Megens
A: 

make it easy.. use backtracking.. write it recursive and it shouln't be to much work

Dimitr
i am ignorant of backtracking. Anyway i will google out some. Thanks :)
ragsagar
A: 

Check out this implementation http://pythonsudoku.sourceforge.net/.

Juanjo Conti
thanks for that link! :)
ragsagar