When I received a booklet with Sudoku puzzles as a present, I couldn't help seeing an Excel spreadsheet... I started solving the puzzles using a pencil only, but after a few days I found it a bit boring, as there was no challenge left - it became routine.
And what do we do when a task becomes a routine? Write a macro to do it faster :-)
So, on a boring afternoon I wrote this macro that can solve all (at least all I have seen until now) Sudoku puzzles.
It first uses some logic to check all possible values for all cells. When there are still cells left with more than one possible number, it switches to a brute-force attack, simply trying all possible options until one works.
I created an interesting recursive routine that uses an extra sheet as a 'stack' to save intermediate solutions so that we can 'fall back' in case a chosen option didn't work out.
It's probably not the most elegant way to solve the puzzles, but it works!
After several years (the original version was written in 2006) I finally updated this macro to solve a few bugs that have been reported over the years. The new version (2012.11) has the following improvements:
- Detects more unsolvable puzzles (would error out instead)
- Does not end with illegal results (double numbers in row or column)
- Shows the time it took to solve the puzzle
- Some general code clean-up
There are still possibilities to improve the code, making it faster, etc. But the most complex puzzle I've ever seen is solved on a reasonably modern system in less than 30 seconds, so why would I bother? If I wanted something faster I would write it in C, not in an interpreted macro-language... :)
Many thanks for all the feedback I have received over the years, some with puzzles that would not be solved, or error reports. Special thanks go to Hendrik Breukink, Jorgen Jensen and Tony Chen.
So the challenge is open again!
I really think it will handle any puzzle with a valid solution now! But, if you discover a Sudoku puzzle my solver cannot handle, I'll mention your submission on my page here! (and improve it so that it will...)
The VBA code of the macro is open for everyone to study (and copy if it pleases you...), as all software should be.
You can get in touch with me from this page.