Dave Campbell
Dave Campbell
Sudoku Solver in Matlab
Monday, March 3, 2014
First I check each row, column, and block to see if a value is already present and delete these points from the ‘potential’ array.
If only one value is left for a location it gets filled into the map.
If a value has only one potential location within a block it gets filled into the map.
That will solve all of the easy sudoku puzzles right there, but the hard ones are hard because you have to assume a value fits somewhere and then check for a breakdown in the logical rules, so I’ve coded this in there as well. If a logical breakdown occurs then the assumed value is discarded and we try again with another assumption. To make it simple these assumed values are selected where a value could be in only one of two places.
There’s a lot of coding shortcuts to avoid loops that could be done but sudoku boards are small and fast with inefficient code. Plus my goal was to algorithmically show how to automate the steps I’d take so I left the code in it’s simpler less efficient form.
Now the slow part is entering the original sudoku matrix. That of course could be done by OCR with a camera but the fun part is coding up the sudoku (not solving it by hand).
Now, if only I could do this to solve the Sunday crossword...
Try running one of these example files and the code on the side:
The ‘fiendishly hard’ puzzle 1130357764 from
is in the image at the top of the page
Saturday morning while reading the Winnipeg free press I found the Sudoku puzzle. While struggling through the ‘hard’ sudoku for a while I thought ‘this would be faster and less error prone if I just coded up my workflow in Matlab.’ So here it goes!
I use a matrix ‘map’ of the sudoku board and a ‘potential’ array of dimensions [row, column, value] specifying whether or not a value could potentially fill a row, column location.