As many have already noted Sudoku can be described as an Exact Cover problem and can therefore be solved using Don Knuth's Algorithm X. Knuth himself has written an implementation of Algorithm X called Dancing Links which does just that.
For more information on Dancing Links, see Wikipedia.
A compact implementation of Algorithm X written in Python can be found here.
Altough there are many implementations of Algorithm X and Dancing Links out there I was yet to find an implementation written in CSharp. After spending more then enough time on Google, yet unable to find anything useful in written in CSharp, I decided to write it myself. My implementation of Dancing Links is based on thisimplementation written i Java. My implementation is tuned for solving Sudoku. Some parts of Algorithm X has been removed in order to boost performance but the code is probably still useful for anyone wanting to implement Algorithm X in CSharp.
I recommend reading the article associated with the Java-implementation as it contains a thorough description of the inner workings of Algorithm X, something which I won't provide here. I'm lazy. ;)
As a final note before we look at the code. The implementation is not only able to solve any given Sudoku puzzle. It's also capable of finding out exactly how many possible solutions are available. You could use this functionality to write a Sudoku puzzle-generator that is capable of generating puzzles for different skill levels.
The implementation is based on four classes.
Node.cs
Represents a node in the graph created by Algorithm X. Contains references to its neighbours, column and row and a label.
ColumnNode.cs
Inherits from Node and represents a column node.
DLArena
The actual Dancing Links implementation
DLSudoku
Support class that converts a Sudoku puzzle into a data structure that Algorithm X understands.
Complete code listing can be found here.
Solution requires Visual Studio 2008.
Inga kommentarer:
Skicka en kommentar